切换案例与穿透?
我正在查找与在Bash中的逐句情况(理想情况下不区分大小写)switch语句正确的语法。 在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_supposed_to_do()应该被触发。 
 对“或”使用竖线( | )。 
 case "$C" in "1") do_this() ;; "2" | "3") do_what_you_are_supposed_to_do() ;; *) do_nothing() ;; esac 
 最近的bash版本允许使用;&而不是;;  :他们还允许通过使用;;&恢复案件检查。 
 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" | ?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 
-  除非你喜欢定义它们,否则不要在bash中的函数名后面使用()。
-  如果匹配2或3使用[23]
-  静态string的情况下应该用''而不是""括起来
 如果用""括起来,解释器(不必要地)试图在匹配之前在值中扩展可能的variables。 
 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没有打到任何时候,因为它会匹配的第一个案件。 
 如果需要的话,可以省略;; 在第一种情况下也继续在以下情况下对比赛进行testing。  ( ;;跳转到esac ) 
尝试这个:
 case $VAR in normal) echo "This doesn't do fallthrough" ;; special) echo -n "This does " ;& fallthrough) echo "fall-through" ;; esac