Hai Le Hai Le - 10 days ago 6
Bash Question

Case Statements with multiple expression or conditions

I want to write a case statement with multiple expression like such:

a=1
b=0
c=1
d=0
case ${a}+${b}+${c}+${d} in
*_1|1_*|*_1|*_1)
echo "it's 1,1,1,1";;
*_1|*_1|*_1|*_0)
echo "it's 1,1,1,0";;
*_1|0_*|1_*|0_*)
echo "it's 1,0,1,0";;
esac


But this doesn't print what I was expecting.

Answer

It appears to me that you're trying to match the concatenation of those four variables; maybe you want to do something other than print the value (that you've painstakingly already determined), but here's how you could do that:

#!/bin/sh

a=1
b=0
c=1
d=0
case ${a}${b}${c}${d} in
  (0000)
        echo "it's 0000"
        ;;
  (0001)
        echo "it's 0001"
        ;;
  (0010)
        echo "it's 0010"
        ;;
  (0011)
        echo "it's 0011"
        ;;
  (0100)
        echo "it's 0100"
        ;;
  (0101)
        echo "it's 0101"
        ;;
  (0110)
        echo "it's 0110"
        ;;
  (0111)
        echo "it's 0111"
        ;;
  (1000)
        echo "it's 1000"
        ;;
  (1001)
        echo "it's 1001"
        ;;
  (1010)
        echo "it's 1010"
        ;;
  (1011)
        echo "it's 1011"
        ;;
  (1100)
        echo "it's 1100"
        ;;
  (1101)
        echo "it's 1101"
        ;;
  (1110)
        echo "it's 1110"
        ;;
  (1111)
        echo "it's 1111"
        ;;
  (*)
        echo "it's something else"
        ;;
esac