Question

is it possible to use multiple variables in a CASE statement? And if so, what is the syntax? I'm trying to use one but can't seem to get it right. I want the statement to be

case $ch+$sys in
*+lin|02+*) at=C2   ;;
*+rin|02+*) at=O57   ;;
*+lin|05+*) at=C1   ;;
*+rin|05+*) at=O123   ;;
esac

If one of the variables does not satisfy the conditions then an error message must be displayed!

Was it helpful?

Solution

My other answer turned out to not work in all cases and i had missed the most simple answer by overthinking it

You just need to have one condition that is a concatenation of both.

The *) ive put at the end is the default case for anything that doesnt match the cases above.

case $ch+$sys in
    02+lin) at=C2   ;;
    02+rin) at=O57   ;;
    05+lin) at=C1   ;;
    05+rin) at=O123   ;;
    *) echo Not worked ;;

esac

OTHER TIPS

The case statement (as lots of things in shell programming) only works on strings. How you build those strings, maybe out of several variables, is completely up to you. If you combine several variables using sth like +, please keep in mind that the chosen combination character can in principle be part of the values. So one+two combined with three using the combination character + will result in the same as one combined with two+three. But in typical cases you probably can choose a combination character which you can be sure of to be not part of the values.

So your approach of combining two variables to one string value (using $ch+$sys) is completely valid as long as the + does not appear inside your variables as well. As you did, you just have to use corresponding match values in the different cases, that's it.

From what you posted I cannot derive the semantics of your code (names like ch and sys and values like lin and rin are too ambiguous for that). So please be more elaborate about the "conditions" you mention in your last sentence.

What your code currently does is sth like this in pseudo code:

if sys = "lin" or ch = "02" then at ← C2
elif sys = "rin" or ch = "02" then at ← 057
elif sys = "lin" or ch = "05" then at ← C1
elif sys = "rin" or ch = "05" then at ← 0123

And this is probably nonsense because at least the last case never can happen (either the second or the third case would happen then and thus prevent the last case).

So maybe you want to rephrase what you in fact wanted, then we can give clearer advice on how to achieve it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top