When I use below code in Ubuntu terminal, it works fine:
rm !(*.sh) -rf
But if I place the same line code in a shell script (clean.sh) and run the shell script from terminal, it throws an error:
clean.sh script:
#!/bin/bash
rm !(*.sh) -rf
The error I get:
./clean.sh: line 2: syntax error near unexpected token `('
./clean.sh: line 2: `rm !(*.sh) -rf'
can you help?
rm !(*.sh)
is aextglob
syntax which means remove all files except the ones that have the.sh
extension.In your interactive
bash
instance, the shell optionextglob
is on :Now as your script is running in a subshell, you need to enable
extglob
by adding this at the start of the script :So your script looks like :
EDIT :
To remove all files except
.sh
extension ones useGLOBIGNORE
(as you don't want to enableextglob
) :Example :
Ok, it's a cross-post, but I have to write an answer. ;)
You could use
find
insteadYou need to turn
extglob
on: