Why does pattern "*.so?(.*)" produce a syntax error in a script but not on command line?

357 views Asked by At

The pattern is a little unusual because I added the trailing "?(.*)" portion. It works on command line as I expected but I get a syntax error for the same in a script.

$ bash --version
GNU bash, version 4.3.11(1)-release (i686-pc-linux-gnu)
...
$ cat x.sh
touch a.so a.so.1
ls *.so?(.*)
rm *.so?(.*)
$ touch a.so a.so.1
$ ls *.so?(.*)
a.so  a.so.1
$ rm *.so?(.*)
$ ls
x.sh
$ bash x.sh
x.sh: line 2: syntax error near unexpected token `('
x.sh: line 2: `ls *.so?(.*)'
$
1

There are 1 answers

5
Tom Fenech On BEST ANSWER

You are using an extended glob but these aren't enabled by default within a script. In order to using them, they must be explicitly enabled. You can do so by adding this before the line:

shopt -s extglob

To disable them later on in the script, you can use shopt -u extglob.

As chepner rightly points out, this feature isn't enabled by default in the interactive shell, either. Presumably, this line is present either in one of your system-wide startup scripts or one of your personal ones.