我正在寻找切换语句的正确语法,在Bash的情况下(理想情况下不区分大小写)。 在PHP中,我将像这样编程:

switch($c) {
    case 1:
        do_this();
        break;
     case 2:
     case 3:
        do_what_you_are_supposed_to_do();
        break;
     default:
        do_nothing(); 
}

我想在Bash中同样:

case "$C" in
    "1")
        do_this()
        ;;
    "2")
    "3")
        do_what_you_are_supposed_to_do()
        ;;
    *)
        do_nothing();
        ;; 
esac

这在某种程度上不起作用:当$C为2或3时,函数do_what_you_are_should_to_do()应该被触发。


当前回答

使用竖线(|)表示“或”。

case "$C" in
"1")
    do_this()
    ;;
"2" | "3")
    do_what_you_are_supposed_to_do()
    ;;
*)
    do_nothing()
    ;;
esac

其他回答

使用竖线(|)表示“或”。

case "$C" in
"1")
    do_this()
    ;;
"2" | "3")
    do_what_you_are_supposed_to_do()
    ;;
*)
    do_nothing()
    ;;
esac

在bash中,不要在函数名后面使用(),除非你想定义它们。 如果匹配2或3,则使用[23] 静态字符串情况应包含“而不是”

如果用""括起来,解释器(不必要地)在匹配之前尝试展开值中可能的变量。

case "$C" in
'1')
    do_this
    ;;
[23])
    do_what_you_are_supposed_to_do
    ;;
*)
    do_nothing
    ;;
esac

对于不区分大小写的匹配,你可以使用字符类(比如[23]):

case "$C" in

# will match C='Abra' and C='abra'
[Aa]'bra')
    do_mysterious_things
    ;;

# will match all letter cases at any char like `abra`, `ABRA` or `AbRa`
[Aa][Bb][Rr][Aa])
    do_wild_mysterious_things
    ;;

esac

但是abra没有命中,因为它会被第一个情况匹配。

如果需要,你可以省略;;在第一种情况下,继续测试匹配在以下情况下也。(;;跳转到esac)

最近的bash版本允许使用;&来代替;;: 它们还允许通过使用;;& there来恢复case检查。

for n in 4 14 24 34
do
  echo -n "$n = "
  case "$n" in
   3? )
     echo -n thirty-
     ;;&   #resume (to find ?4 later )
   "24" )
     echo -n twenty-
     ;&   #fallthru
   "4" | [13]4)
     echo -n four 
     ;;&  # resume ( to find teen where needed )
   "14" )
     echo -n teen
  esac
  echo 
done

样例输出

4 = four
14 = fourteen
24 = twenty-four
34 = thirty-four

如果值是整数,则可以使用[2-3],对于非连续值可以使用[5,7,8]。

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    1)
        echo "one"
        ;;
    [2-3])
        echo "two or three"
        ;;
    [4-6])
        echo "four to six"
        ;;
    [7,9])
        echo "seven or nine"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

如果值是字符串,则可以使用|。

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    "one")
        echo "one"
        ;;
    "two" | "three")
        echo "two or three"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

试试这个:

case $VAR in
normal)
    echo "This doesn't do fallthrough"
    ;;
special)
    echo -n "This does "
    ;&
fallthrough)
    echo "fall-through"
    ;;
esac