user1240076
user1240076

Reputation: 303

Use Variable with multiple options in Case statement

Is it possible to do something like the following (and how ?)(,resp. why not ?):

MATCH="--opt1 | --opt2"
while true ; do
    case $1 in
        $MATCH)
             echo "option $2" found;
             shift 2;;
        *)
             unknown option; exit 1;
    esac
done

For reason I dont understand this doesnt work. However, having only one alternative like MATCH="--opt1" is fine.

Edit 1: possible Solution

Instead of going with case statement one could simply check if the given option occurs in a string of multiple allowed options, for instance by using grep and if. To do it full dynamically one could consider the follwoing solution, which might also combined with or embedded within case statement:

while true ; do
if [ -n "$(echo $MATCHES|grep -- $1)" ]; then
    echo "found option $1 with value $2"
    shift 2
fi
done

Upvotes: 2

Views: 4521

Answers (1)

chepner
chepner

Reputation: 530960

The pipe character, when embedded in a parameter value, is treated literally, not as syntax. You'll have to use multiple strings:

while true; do
    case $1 in
       $MATCH1 | $MATCH2 )
       # etc

Upvotes: 10

Related Questions