Skip to content
Advertisement

Better way of using the redirection symbol in conjunction with find -exec

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:

JavaScript

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:

JavaScript

If you want to only use bash, you could use a while loop:

JavaScript

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:

JavaScript

although I don’t like that solution.

Advertisement