2

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

grochmal
  • 8,657

1 Answers1

6

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.

Kusalananda
  • 333,661