I was writing a script to clean a text file from a directory (I know,it's a bad idea but I really need it) and I wrote this:

var=$(ls -p /direcotry/to/file | grep -v /)
truncate -s 0 $var

The problem is that when I run the script all the files from that directory are copied to the directory from which I launch the script and the files from the original directory remain untouched. Why this behavior and how can I fix it?


That is because the output of your ls command is just the list of file names, not their path. The truncate command will, therefore, recreate the same file names as empty files in the current directory.

In addition, your approach, even if done correctly, will break on even slightly strange filenames (those that contain a space, for example), let alone more complex ones (with newlines or backslashes etc).

First of all, you don't need to script it. You could just pass the list of files to truncate:

truncate -s 0 /direcotry/to/*

If truncate encounters a directory, it will just print an error and move to the next item:

truncate: cannot open ‘foo’ for writing: Is a directory

To do it more cleanly, you could use find:

find /direcotry/to/file -type f -exec truncate -s {} +

Or a shell glob:

for f in /direcotry/to/file; do
    [ -f "$f" ] && truncate -s "$f"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.