nino
nino

Reputation: 678

how to tell find command to only remove contents of a directory

I am using find to get both files and dirs inside $dest_dir and remove them:

dest_dir="$HOME/pics"
# dest_dir content:
#  dir1
#  dir2
#  pic1
#  pic2

find $dest_dir -maxdepth 1 -exec rm -rf {} \;

I also tried -delete instead of the -exec rm -rf {} \; section, but it can't remove non-empty directories.

Upvotes: 0

Views: 362

Answers (2)

anubhava
anubhava

Reputation: 786101

You can use this find command:

find "$dest_dir" -maxdepth 1 -mindepth 1 -exec rm -rf {} +

Option -mindepth 1 will find all entries inside "$dest_dir" at least one level down and will skip "$dest_dir" itself.

Upvotes: 1

tripleee
tripleee

Reputation: 189936

If you pass a directory name to rm -rf it will delete it, by definition. If you don't want to recurse into subdirectories, why are you using find at all?

rm "$dest_dir"/*

On the other hand, if you want to rm -rf everything inside the directory ... Do that instead.

rm -rf "$dest_dir"/*

On the third hand, if you do want to remove files, but not directories, from an arbitrarily deep directory tree, try

find "$dest_dir" -type f -delete

or somewhat more obscurely with -execdir and find just the directories and pass in a command like sh -c 'rm {}/*', but in this scenario this is just clumsy and complex.

Upvotes: 2

Related Questions