Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nonzero return code although find -exec rm works

Tags:

linux

shell

I'm on a linux system I wonder what is wrong with the following execution of find:

mkdir a && touch a/b                      
find . -name a -type d -exec echo '{}' \; 
./a
find . -name a -type d -exec rm -r '{}' \;
find: `./a': No such file or directory

The invocation of echo is just for testing purposes. I would expect the last command to remove the directory './a' entirely and return 0. Instead it removes the directory and generates the error message. To repeat, it does remove the directory! What is going on?

like image 365
Thomas Avatar asked Sep 16 '12 19:09

Thomas


2 Answers

rm executes without a problem. The issue is that find is confused, since it knew the directory ./a was there, it tries to visit that directory to look for directories named a. However, find cannot enter the directory, since it was already removed.

One way to avoid this is to do

find -name a -type d | xargs rm -r

This will let the find move along before the rm command is executed. Or, you can simply ignore the error in your original command.

like image 130
epsalon Avatar answered Sep 20 '22 17:09

epsalon


Based on epsalon's comment the solution is to use the -depth option which causes the deeper files to be visited first.

find . -depth -name a -type d -exec rm -r '{}' \;

does the trick. Thanks a bunch!

like image 37
Thomas Avatar answered Sep 19 '22 17:09

Thomas