Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 769
user1240076 Avatar asked Jan 31 '26 10:01

user1240076


1 Answers

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
like image 98
chepner Avatar answered Feb 03 '26 00:02

chepner