2

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

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

3 Comments

Good one. So it only matches when the parameter given is exactly "--opt1 | --opt2"
which means, that the "Match-clause" cannot be created generically ?!
@user1240076 Correct. Your code is clearer when you keep data and synxtax/operators separate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.