My goal is to empty every file in a directory. I DON’T want to actually delete the file, I just want to delete it’s contents.
If you want to do this with a single file you can do > file.txt
If I want to run this operation on every file in a directory I can do this:
find . -exec /bin/bash -c '> {}' ;
Notice how the above command has to call /bin/bash
. This is because simply running the command like this, find . -exec > {} ;
says find: invalid argument ;' to -exec'
I suspect this is because the redirection symbol is confusing the command.
I would like to run this command without needing to run /bin/bash
within -exec
How can this be done?
Advertisement
Answer
One easy way to do this is by using truncate
:
find -type f -exec truncate -s0 {} +
If you want to only use bash, you could use a while
loop:
find -type f -print0 | while IFS= read -r -d '' file; do > "$file" done
Finally, if you didn’t mind using bash -c
, it would be better to do it as follows to avoid calling bash so many times:
find -type f -exec bash -c 'for file; do > "$file"; done' - {} +
although I don’t like that solution.