ElpieKay
ElpieKay

Reputation: 30868

Is it possible to generate dynamic patterns for case statement in Bash?

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.

Upvotes: 0

Views: 392

Answers (1)

chepner
chepner

Reputation: 531165

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.

Upvotes: 2

Related Questions