0

This question already has an answer here:

I'm definitely doing something wrong but can't figure this one out. When I run rm -rf on directories through find I get a No such file or directory but it does not happen when I do it manually. Assuming the following directory tree:

[~]$ mkdir -p blueprints/blog
[~]$ find
.
./blueprints
./blueprints/blog

I create directories and add files to them:

[~]$ mkdir ./blueprints/blog/__pycache__ ./blueprints/__pycache__ ./__pycache__
[~]$ touch ./blueprints/blog/__pycache__/dummy.pyc ./__pycache__/dummy.pyc

I am sure I have them:

[~]$ find . -type d -name '__pycache__'
./blueprints/blog/__pycache__
./blueprints/__pycache__
./__pycache__

But removing them causes find to print an error:

[~]$ find . -type d -name '__pycache__' -exec rm -rf {} \;
find: ‘./blueprints/blog/__pycache__’: No such file or directory
find: ‘./blueprints/__pycache__’: No such file or directory
find: ‘./__pycache__’: No such file or directory

They get removed alright but what is happening there?


Doing it in a different way does not provoke the error:

[~]$ mkdir ./blueprints/blog/__pycache__ ./blueprints/__pycache__ ./__pycache__
[~]$ touch ./blueprints/blog/__pycache__/dummy.pyc ./__pycache__/dummy.pyc
[~]$ find . -type d -name '__pycache__' -exec echo rm -rf {} \; | sh

Why does find report that error? As far as I am aware if -exec is present the -print action does not get invoked (that's what I suspected at first).

I have replicated the above using both find 4.6.0 and find 4.5.11

marked as duplicate by Community Feb 17 '17 at 21:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    Does adding -depth help? – iruvar Feb 17 '17 at 21:01
  • @iruvar - yeah, it does! I get it now, find executes -exec and then tries to walk deeper into the __pycache__ directory. You should add that as an answer. – grochmal Feb 17 '17 at 21:07
3

When you delete the directory with rm -rf, find still tries to enter it after deleting it (it has no notion of what rm is doing). That's where the error happens.

You should add the -depth flag.

From the POSIX find manual:

-depth

The primary shall always evaluate as true; it shall cause descent of the directory hierarchy to be done so that all entries in a directory are acted on before the directory itself. If a -depth primary is not specified, all entries in a directory shall be acted on after the directory itself. If any -depth primary is specified, it shall apply to the entire expression even if the -depth primary would not normally be evaluated.

  • That's what I get from not reading the man with enough attention. Thanks – grochmal Feb 17 '17 at 21:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.