2

I'm using the command ls files/@(*.text|*.txt|*.xt) to get all files that end with any of the patterns.

When I run it in the shell I get this result

$ ls files/@(*.text|*.txt|*.xt)
files/f1.text  files/f1.txt  files/f1.xt

When I create a bash script, it throws the error ls: cannot access files/@(*.text|*.txt|*.xt): No such file or directory

Here is a copy of my bash script

#!/bin/bash

ls files # this one works
ls files/@\(*.text\|*.txt\|*.xt\) # This doesn't work

full output when running the bash script

$ ./testScript.sh 
files/f1.text  files/f1.txt  files/f1.xt
ls: cannot access files/@(*.text|*.txt|*.xt): No such file or directory

Confirmed the shell is a bash shell

$ echo $SHELL
/bin/bash

I also tried:

  • ls files/@\(*.text|*.txt|*.xt\) - throws line 4: *.xt): command not found
  • ls files/@(*.text|*.txt|*.xt) - throws line 4: syntax error near unexpected token ('`
  • running with sh ./testScript.sh - same error as original error.
  • using /files/@(*.text|*.txt|*.xt) - no luck (same error as above in this list)
Ammar Hussein
  • 5,534
  • 5
  • 18
  • 37
  • 1
    If you run `echo $SHELL` manually what is the output? Next, if you run `sh ./testScript.sh` do you still receive the same error? Finally can you update your ls command to `ls ./files/@(*.text|*.txt|*.xt)` (path updated) and let us know if the error is the same? – PCDSandwichMan Oct 30 '22 at 03:25
  • 1
    post the output of `shopt | grep extglob` both from the command line and within the script. `@(pattern-list)` only matches one of the patterns if `extglob` is set. There is also the caveat that if your script is started with a EUID or EGID that does not match the real UID or GID, then `$SHELLOPTS` and `$BASHOPTS` set in the parent are ignored. – David C. Rankin Oct 30 '22 at 03:44
  • Edited the question to add more information, thanks @PCDSandwichMan. @DavidC.Rankin Running `shopt | grep extglob` Result on terminal: `extglob on` Result from the script: `extglob off` Seems like that root causes the problem, need to figure out how to fix that – Ammar Hussein Oct 30 '22 at 04:12
  • @PCDSandwichMan The value of $SHELL is completely unrelated. It does not indicate which shell is currently running, nor which shell would be run. – William Pursell Oct 30 '22 at 14:42

1 Answers1

0

You enable extglob in your script with shopt -s extglob.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38