Search code examples
findcygwin

find revisiting already visited folder


When using below command to list folders as they get deleted

$ find . -type d -name .idea -exec sh -c "echo {}; rm -rf {}" \;
    ./.idea
    find: ‘./.idea’: No such file or directory
    ./folder1/.idea
    find: ‘./folder1/.idea’: No such file or directory
$

no idea why deleted folders are being revisited by find producing error of

No such file or directory

Solution

  • find processes each directory's contents after the directory itself.

    So you need to add -depth option :

    find . -depth -type d -name .idea -exec sh -c "echo {}; rm -rf {}" \;
    

    Update

    You can do following expriment, first

    mkdir -p .idea/folder1/.idea
    
    # Step 1
    find . -type d -name .idea -exec sh -c "echo rm -rf {}" \;
    # rm -rf ./.idea
    # rm -rf ./.idea/folder1/.idea
    
    # Step 2
    find . -depth -type d -name .idea -exec sh -c "echo rm -rf {}" \;
    # rm -rf ./.idea/folder1/.idea
    # rm -rf ./.idea
    

    You can see that in step 1, find first removes ./.idea and then tries to search the subdirectories to find ./.idea/folder1/.idea.

    Whereas in step 2, find first tries to search the subdirectories to find ./.idea/folder1/.idea and removes ./.idea after that.