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

前端 未结 2 479
傲寒
傲寒 2020-12-31 08:07

UPDATE 2014-03-21

So I realized I wasn\'t as efficient as I could be, as all the disks that I needed to \"scrub\" were under /media and

相关标签:
2条回答
  • 2020-12-31 08:42

    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.

    0 讨论(0)
  • 2020-12-31 08:50

    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! :)

    0 讨论(0)
提交回复
热议问题