Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to write if else condition for 3 Boolean variable

Tags:

bash

I have 3 boolean variables a,b and c. what's the best way to write the if else condition(or some better way) in bash to cover all combinations (refer pic).

for example: a=y,b=y and c=y then echo foo

enter image description here

I can write multiple elseif conditions but is there any alternate way?

like image 375
gamechanger17 Avatar asked Nov 22 '25 15:11

gamechanger17


1 Answers

Not really sure of what you're expecting precisely, but if you need to check every possible combination, and your variables can only have two values: y or n, then you can use a case statement:

case "$a$b$c" in
    yyy) echo bar ;;
    yyn) echo foo ;;
    yny) echo foo ;;
    ynn) echo foo ;;
    nyy) echo bar ;;
    nyn) echo foo ;;
    nny) echo foo ;;
    nnn) echo foo ;;
    *) echo error; exit 1 ;;
esac
like image 74
yolenoyer Avatar answered Nov 24 '25 07:11

yolenoyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!