Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find: Cannot chdir to directory error message after deleting directories

I am working on a project to automatically delete specific directories which are older than a day. I have got the following piece of code working:

find Directory/ -type d -name "Directory.To.Delete.*" -mtime +1 -exec rm -rf {} \;

It runs fine and deletes the directory (and contents) as expected, however it always ends with an error:

find: cannot chdir to Directory/ : No such file or directory

Is there a way to run this code without facing this error? I don't understand why this code is trying to chdir after deleting the directory.

like image 670
DevHouse Avatar asked Dec 01 '25 09:12

DevHouse


2 Answers

Add -prune before -exec; that will stop find from entering matches directories:

.... -mtime +1 -prune -exec ...
like image 136
Aaron Digulla Avatar answered Dec 03 '25 10:12

Aaron Digulla


Add -depth before -type d will also stop find from entering matched directories.

# mkdir 1
# mkdir 2
# touch -d yesterday 1
# find . -depth -type d -mtime +0 -exec rm -rf {} \;
# ls
2

From man find:

   -prune True;  if  the file is a directory, do not descend into it. If -depth is given, false; no effect.  Because -delete implies -depth, you cannot usefully use -prune and -delete together.
like image 34
Andy Thompson Avatar answered Dec 03 '25 11:12

Andy Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!