0

For example,

a="1|2|3"
b=3
case $b in
$a )
echo in
;;
* )
echo out
;;
*)
esac

I'd like $a to be expanded as 1|2|3. But seems it cannot work as expected. Thanks for any suggestion.

ElpieKay
  • 27,194
  • 6
  • 32
  • 53

1 Answers1

2

The problem is that | is not part of the pattern, but part of the case statement's syntax that separates two patterns. The following would work:

foo=3
b1=1
b2=2
b3=3

case $foo in
    $b1|$b2|$b3) echo match ;;
esac

The | needs to be visible to the parser before parameter expansion occurs to act as a pattern separator. If the | is produced by a parameter expansion, it is treated as a literal character to match as part of a pattern.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    A `case $b in +($a) ) echo in ;; ` also works correctly provided that a `shopt -s extglob` is in effect. –  Dec 22 '16 at 19:34
  • Yeah, I considered adding a note about that when I saw @choroba's comment, but then decided to just explain why placing a bar in a parameter alone didn't work. – chepner Dec 22 '16 at 19:38