find command in bash script resulting in "No such file or directory" error only for directories?

tl;dr - Pass -prune if you're deleting directories using find.

For anyone else who stumbles on this question. Running an example like this

find /media/disk3 -type d -name .AppleDouble -exec rm -rf {} \;

results in an error like

rm: cannot remove 'non_existent_directory': No such file or directory

When finding and deleting directories with find, you'll often encounter this error because find stores the directory to process subdirectories, then deletes it with exec, then tries to traverse the subdirectories which no longer exist.

You can either pass -maxdepth 0 or -prune to prevent this issue. Like so:

find /media/disk3 -type d -name .AppleDouble -prune -exec rm -rf {} \;

Now it deletes the directories without any errors. Hurray! :)


You don't need to escape DOT in shell glob as this is not regex. So use .AppleDouble instead of \.AppleDouble:

find $DIRTY_DIR -name .AppleDouble -exec rm -rf '{}' \;

PS: I don't see anywhere $COUNTER being incremented in your script.