0

How do I find a directory and delete all it's content but not the directory itself?

find -type -d -name 'Tmp' -exec rm -rf {} \;

But this also deletes 'Tmp' directory.

Thanks in advance.

1

Here's one way of doing it:

find . -type d -name 'Tmp' -exec sh -c 'rm -r "$0"/*' {} \;

Personally I would prefer to do this with bash, though:

shopt -s globstar
rm -r ./**/Tmp/*

With this, you can also easily ensure you're deleting hidden dotfiles, too:

shopt -s globstar dotglob
rm -r ./**/Tmp/*
  • I am not experienced with bash at all. What does shopt and globstar reference to? – John Dec 23 '13 at 19:43
  • shopt is the command to set options within bash -- shopt -s globstar sets (turns on) the globstar option. When this is set, ** acts as a recursive glob -- so **/*.foo would search for every *.foo in the current directory and within all subdirectories. dotglob is another shell option, which makes globs match files beginning with a dot (which are hidden by default). I normally leave shopt -s globstar extglob in my ~/.bashrc (extglob being another useful shell option). – evilsoup Dec 23 '13 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.