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

Time:08-06

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?

CodePudding user response:

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

CodePudding user response:

I would do it with an associative array:

declare -A arr=(
   [yyy]=foo
   [ynn]=bar
   [yyn]=bar
   [nyn]=bar
   [nyy]=foo
   [nny]=bar
)

echo ${arr["$a$b$c"]}

CodePudding user response:

You will normally encounter 8 cases but if those 6 are all you face, then you can try something like

if [[ $b && $c]];
then
  echo foo;
else
  echo bar;
fi

This will work because regardless of what a holds, the result foo is y only if b and c are y (True). The rest are just boo. If you want more accurate boolean expression you can try using "k-maps".

CodePudding user response:

case $a/$b/$c in
    [ny]/y/y)       echo foo ;;
    [ny]/[ny]/[ny]) echo bar ;;
    *)              echo error; exit 1 ;;
esac

By adding a separator string (the / in $a/$b/$c), invalid input such as a=yyy b= c= will be rejected as an error.

  •  Tags:  
  • bash
  • Related