Shahar Hamuzim Rajuan
Shahar Hamuzim Rajuan

Reputation: 6129

Deleting a directory starting with a specific string in shell script

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

Upvotes: 1

Views: 1091

Answers (2)

anubhava
anubhava

Reputation: 785108

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.

Upvotes: 5

scottgwald
scottgwald

Reputation: 609

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;

Upvotes: 1

Related Questions