Bash script to remove all files and directories except specific ones

mario go picture mario go · Nov 5, 2013 · Viewed 20.8k times · Source

I am trying to write a very simple Bash shell script that will cd in a specific directory, it will remove all files and directories except some few selected ones and then cd back to the original dir.

My code is:

#!/bin/bash 
cd /path/to/desired/directory
shopt -s extglob
rm !\(filename1\|filename2\|filename3\) -rf
cd -

I have tried many different ways to write the symbols '(' and '|', with single or double quotes or backslash but nothing worked. Note, that shopt -s extgloband rm !(filename1|filename2) -rf work fine outside a script.

Probably I am committing a standard and fundamental bash-scripting error that I cannot see, but experience is to come...

Any suggestions!? Thanks in advance.

Answer

Adam Rosenfield picture Adam Rosenfield · Nov 5, 2013

Two problems I can see right off the bat:

  • The -rf argument to rm must come before the filenames
  • The extglob specifiers !, (, | and ) should not be escaped with backslashes

Try this instead:

rm -rf !(filename1|filename2|filename3)

If it's still not working, remove the -f argument, and you'll get error messages about what's going wrong instead of silently suppressing them. To print out the name of each file removed, you can add the -v option as well.