Pattern match does not work in bash script

Ogd*_*den 13 linux bash glob extglob

Using the pattern match !("file1") does not work within a bash script but will work on the command line.

For example:

ls  !("file1"|"file2")
Run Code Online (Sandbox Code Playgroud)

This will list all files in directory except file1 and file2.

When that line is executed in a script this error is displayed:

./script.sh: line 1: syntax error near unexpected token `('
./script.sh: line 1: ` ls  !("file1"|"file2") ' 
Run Code Online (Sandbox Code Playgroud)

Regardless what is used rm -v !("file1"). The same error takes place. What is going on here why does this not work in a script?

tri*_*eee 12

The extended glob syntax you are trying to use is turned off by default; you have to enable it separately in each script where you want to use it.

shopt -s extglob
Run Code Online (Sandbox Code Playgroud)

Scripts should not use ls though I imagine you were using it merely as a placeholder here.


Raf*_*ael 5

Globbing doesn't work that way unless you enable extglob shell opt. Instead, I recommend using find:

find . -maxdepth 1 -not -name '<NAME>' -or -name '<NAME>' -delete
Run Code Online (Sandbox Code Playgroud)

before running this command with -delete ensure the output is correct