2

This code running on GNU bash, version 5.0.7(1)-release (x86_64-redhat-linux-gnu):

var="r=x"
case "$var" in
        r=?(x|xy|xyz))
                echo "suchess"
                ;;
esac

Is generating this error:

bash: test.sh: line 3: syntax error near unexpected token `('
bash: test.sh: line 3: `        r=?(x|xy|xyz))'

Cannot for the life of me figure out why... tested code found here and it works.

Inian
  • 80,270
  • 14
  • 142
  • 161
RJ Cole
  • 2,592
  • 3
  • 18
  • 23

2 Answers2

3

Argh. So this is embarrassing. I found the answer almost as soon as I posted this. The answer is in the link in my question. I needed to add:

shopt -s extglob

To the start of script.

Hope this helps someone else in the future.

Answer found here: How to use patterns in a case statement?

RJ Cole
  • 2,592
  • 3
  • 18
  • 23
2

Also, optionally, you don't have use/set the extglob option explicitly and do this match with a case statement. If you are using bash, the test operator provides this match when using with ==

var="r=x"
if [[ $var == r=?(x|xy|xyz) ]]; then
    printf '%s\n' "success"
fi

Ensure you do not quote the glob pattern in the right side of the == operator. Either use it above or do a variable assignment to store the glob and do an unquoted comparison

glob="r=?(x|xy|xyz)"
if [[ $var == $glob ]]; then
Inian
  • 80,270
  • 14
  • 142
  • 161