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.
Add -prune before -exec; that will stop find from entering matches directories:
.... -mtime +1 -prune -exec ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With