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

前端 未结 2 487
傲寒
傲寒 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: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! :)

提交回复
热议问题