Cindy Almighty
Cindy Almighty

Reputation: 933

Why does "find . -name somedir -exec rm -r {} \;" exit nonzero whenever it successfully deletes a directory?

I want to find a folder in a known folder but with unknown exact path, thus I must use find. When I find it, I use -exec to remove it, but I cannot evaluate if this has succeeded. Behavior somewhat confuses me; if I don't find the folder, I get return code 0:

>find . -name "testuuu" -exec rm -r {} \;
find: ‘./.docker’: Permission denied
>echo $?
0

But when I do find the folder and manage to delete it, it returns error code 1:

> find . -name "test" -exec rm -r {} \;
find: ‘./.docker’: Permission denied
find: ‘./test’: No such file or directory
> echo $?
1

Is this expected behavior? Why? Further, how can I get return code of "rm" and not "find" and thus evaluate if the folder was deleted?

Upvotes: 0

Views: 707

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295520

Use the -depth option to order a depth-first traversal -- that way find doesn't try to find things under your directory after the directory has already been deleted (an operation which, by nature, will always fail).

find . -depth -name "test" -exec rm -r -- '{}' \;

This option is also turned on by default when you use the -delete action in GNU find to delete content.


By the way -- if there are lots of test directories, you could get better performance by making that -exec rm -r -- {} + (which passes each copy of rm as many filenames as will fit on its command line) instead of -exec rm -r -- {} \; (which starts a new copy of rm for each test that is found), at the expense of no longer collecting individual error codes.

Upvotes: 3

Related Questions