Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've got a /tmp/test directory. In it I've got a mixture of files and directories. One of those directories is /tmp/test/to_be_kept. Now I'd like to know how do I delete all the files and directories apart from /tmp/test/to_be_kept and everything what's in it? Thanks

share|improve this question
shopt -s extglob
rm -r /tmp/test/!(to_be_kept)
share|improve this answer

This will produce some error messages which you can ignore when it tries to re-access directories that have already been removed:

find /tmp/test -mindepth 1 -type d -name to_be_kept -prune -o -exec rm -rf {} \;
share|improve this answer
  • Here is a simple way:

    ls /tmp/test | grep -v to_be_kept | xargs rm -r
  • If you want to delete hidden also:

    ls -a /tmp/test | grep -v to_be_kept | xargs rm -r

Always test the output first!

Try these first without the | xargs rm -r part! If you get the list of files and directories you wanted to delete you may as well apply...

share|improve this answer
+1 for workable solution complete with "safety first" instructions. – David Spillett May 22 '10 at 21:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.