I have temp directories full of junk that all start with __temp__ (e.g. __temp__user_uploads), which I want to delete with a cleanup function. My function attempt is to run:
find . -name __temp__* -exec rm -rf '{}' \;
If I run the command and there are multiple __temp__ directories (__temp__foo and __temp__bar), I get the output:
find: __temp__foo: unknown option
If I run the command and there is only 1 __temp__ directory (__temp__foo), it is deleted and I get the output:
find: ./__temp__foo: No such file or directory
Why doesn’t the command work, why is it inconsistent like that, and how can I fix it?
Use a depth-first search and quote (or escape) the shell metacharacter
*:Explanation
Without the
-depthflag, yourfindcommand will remove matching filenames and then try to descend into the (now unlinked) directories. That’s the origin of the “No such file or directory” in your single__temp__directory case.Without quoting or escaping the
*, the shell will expand that pattern, matching several__temp__whateverfilenames in the current working directory. This expansion will confusefind, which is expecting options rather than filenames at that point in its argument list.