First of all, for safety, let's do our testing with echo !(file1|file2)
instead of rm -rf !(file1|file2)
.
Anyway, bash does some parsing of the entire command line before executing the shopt -s extglob
command. When bash encounters the (
, the extglob
option isn't set yet. That's why you get the error.
Try this instead:
bash -O extglob -c 'echo !(file1|file2)'
In your script, you just need to turn on the option as a separate command line before relying on it:
#!/bin/bash
shopt -s extglob
echo !(file1|file2)
You can actually do this with the -c
flag also:
bash -c 'shopt -s extglob
echo !(file1|file2)'
Or even like this:
bash -c $'shopt -s extglob\necho !(file1|file2)'