Nonzero return code, although find -exec rm works

I am on a linux system. Interestingly, what is wrong with the following find execution:

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 echo call is for testing purposes only. I expect the last command to completely delete the "./a" directory and return 0. Instead, it deletes the directory and generates an error message. To repeat, it deletes the directory! What's happening?

+4
source share
3 answers

rm runs without problems. The problem is that find confused, because he knew that the ./a directory ./a , he is trying to visit that directory to look for directories named a . However, find cannot enter the directory because it has already been deleted.

One way to avoid this is to do

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

This will allow the search to move forward before executing the rm command. Or you can simply ignore the error in the original command.

+10
source

Based on epsalon's comment, the solution should use the -depth parameter, which forces you to visit deeper files first.

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

does the trick. Thanks a bunch!

+6
source

If performance is a problem, use -prune to prevent descending searches in directories named "a":

 find . -name a -type d -prune -exec rm -r '{}' \; 
+4
source

Source: https://habr.com/ru/post/1434490/


All Articles