Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the `find` command in Linux to remove non-empty directories? [closed]

Tags:

linux

find

bash

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?

like image 739
orokusaki Avatar asked Sep 19 '12 03:09

orokusaki


1 Answers

Use a depth-first search and quote (or escape) the shell metacharacter *:

find . -depth -name '__temp__*' -exec rm -rf '{}' \;

Explanation

Without the -depth flag, your find command 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__whatever filenames in the current working directory. This expansion will confuse find, which is expecting options rather than filenames at that point in its argument list.

like image 51
pilcrow Avatar answered Oct 24 '22 21:10

pilcrow