Pattern match does not work in bash script
Asked Answered
R

3

16

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

For example:

ls  !("file1"|"file2")

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") ' 

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?

Repairman answered 6/4, 2019 at 7:12 Comment(2)
Possible duplicate of How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?, List all files that do not match pattern using ls, etc. And related is Why would I not leave extglob enabled in bash?Lashanda
run it using source script.shSpinous
M
17

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

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

Maccaboy answered 6/4, 2019 at 7:17 Comment(0)
M
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

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

Maganmagana answered 6/4, 2019 at 7:17 Comment(0)
L
3

Method with default settings and no external procs:

for f in *; do [[ $f =~ ^file[12]$ ]] || echo "$f"; done
Lucchesi answered 6/4, 2019 at 7:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.