1

In my interactive shell I can store a pattern in a variable

$ targets="?(pcm52|pcm61)"
$ ls -l config/devdesc.$targets
-rw-r--r-- 1 kfa kfa 113 Dec 16 13:43 config/devdesc.pcm52
-rw-r--r-- 1 kfa kfa  14 Dec 16 13:44 config/devdesc.pcm61

But if I create a shell script

targets="?(pcm52|pcm61)"
ls -l config/devdesc.$targets

I get this error running it

$ bash -x /tmp/e.sh
+ targets='?(pcm52|pcm61)'
+ ls -l 'config/devdesc.?(pcm52|pcm61)'
ls: cannot access 'config/devdesc.?(pcm52|pcm61)': No such file or directory

Why does it fail when put into a script?

Léa Gris
  • 17,497
  • 4
  • 32
  • 41
Kjeld Flarup
  • 1,471
  • 10
  • 15
  • 1
    Does this answer your question? [Pattern match does not work in bash script](https://stackoverflow.com/questions/55546727/pattern-match-does-not-work-in-bash-script) – Léa Gris Dec 21 '20 at 13:31
  • @l%c3%a9a-gris Yes that is the exact same problem. Just ran into the how to formulate the right search question. – Kjeld Flarup Dec 21 '20 at 15:00

1 Answers1

7

From Bash manual page:

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized.

So just add shopt -s extglob to the beginning your e.sh script, since it does not inherit that non-default option from your interactive session.

Quasímodo
  • 3,812
  • 14
  • 25
  • 3
    So specifically to "Why does it fail when put into a script?": because you are using an extended glob pattern, support for those depends on a non-default shell option, and that option is not inherited by your script. – John Bollinger Dec 21 '20 at 13:04
  • 1
    Or you could also have noted that this question is a duplicate, because it recurrent and has been addressed here at multiple occasions. – Léa Gris Dec 21 '20 at 13:37