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 extglob
and 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.
Two problems I can see right off the bat:
-rf
argument to rm
must come before the filenames!
, (
, |
and )
should not be escaped with backslashesTry 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.