1

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

9
  • A case statement doesn't "include" variables, see help case. It is case word in ..., which means you could write case "foo" in "foo") echo "foo found" ;; esac. Commented Sep 1, 2016 at 7:09
  • ok , I mean expressions - the syntaxis is case statement in , is there a way to use two expressions in one case statement ? Example : 'case expression1 & expression2 in' or 'case expression1 or expression2 in' ? Commented Sep 1, 2016 at 7:15
  • This might help tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html Commented Sep 1, 2016 at 7:15
  • 1
    In case WORD in , WORD must be a character string. Therefore the problem is how to turn a logical operation result into a string. As I said, the bash arithmetic $((···)) returns a string, unlike [···] and [[···]] do, but their logical outcomes can be checked using $?. Commented Sep 1, 2016 at 8:13
  • 1
    Store the result of a $a or $b in a variable and then use a case statement on that variable. Commented Sep 1, 2016 at 8:21

2 Answers 2

4

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

Comments

2

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

Comments

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.