Deleting a directory starting with a specific string in shell script

983 Views Asked by At

When I'm trying to delete all directories starting with tmp, I used this command:

 find -type d -name tmp* -exec rmdir {} \;

And it does the trick, but this command is exiting with an error code:

find: `./tmp09098': No such file or directory

What causing failing my build.

Can anyone tell me how I can delete those folders without getting the error?

After trying what @anubhava suggested and quoted 'temp*',

find -type d -name 'tmp*' -exec rmdir {} \;

I still get the same error:

find: `./tmp0909565g': No such file or directory

find: `./tmp09095': No such file or directory

When running:

find -type d -name 'tmp*' -exec ls -ld '{}' \;

This is the result:

drwxr-xr-x 2 root root 4096 Jun 16 10:08 ./tmp0909565g
drwxr-xr-x 2 root root 4096 Jun 16 10:07 ./tmp09095
drwxr-xr-x 2 root root 4096 Jun 16 10:08 ./tmp09094544656
2

There are 2 best solutions below

6
On BEST ANSWER

You should quote the pattern otherwise it will be expanded by shell on command line:

find . -type d -name 'tmp*' -mindepth 1 -exec rm -rf '{}' \; -prune

-prune causes find to not descend into the current file/dir.

4
On

This works for me:

    #! /bin/bash

    tmpdirs=`find . -type d -name "tmp*"`

    echo "$tmpdirs" |

    while read dir;
    do
     echo "Removing directory $dir"
     rm -r $dir;
    done;