zlobul
zlobul

Reputation: 375

bash shell script case statement for two variables

I want to create a case statement including two expressions, my imagination is to look like this :

a=true
b=false 

case [ "$a" || "$b"]  in  #<-- how can I do this with a case statement ?

true)echo "a & b are true" ;;
false)echo "a or b are not true" ;;

esac

Is it possible to do it with case instead of if ?

Thanks

Upvotes: 1

Views: 4800

Answers (2)

chepner
chepner

Reputation: 532218

bash doesn't have Boolean constants; true and false are just strings, with no direct way to treat them as Boolean values. If you use the standard encoding of 0 and 1 as Boolean values, you can use $((...)):

a=1  # true
b=0  # false
case $(( a && b )) in
  1) echo 'a && b == true' ;;
  0) echo 'a && b == false' ;;
esac

Upvotes: 2

James Brown
James Brown

Reputation: 37464

This is an example but it's about strings, not real logical expressions:

$ cat > foo.sh
a=true
b=false
case $a$b in        # "catenate" a and b, two strings
    *false*)        # if there is substring false (ie. truefalse, falsetrue or falsefalse) in there
        echo false  # it's false
        ;;
    *)
        echo true   # otherwise it must be true
        ;;
esac

$ bash foo.sh
false

Upvotes: 4

Related Questions