开发者问题收集

具有多个表达式或条件的 Case 语句

2016-11-29
3743

我想编写一个带有多个表达式的 case 语句,如下所示:

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

但是这并没有打印出我期望的内容。

1个回答

在我看来,您正在尝试匹配这四个变量的连接;也许您想做一些除了打印值(您已经煞费苦心地确定了)之外的事情,但是您可以这样做:

#!/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
Jeff Schaller
2016-11-29