嵌套案例 - 为什么必须“;;”放在可能的命令后面而不是直接放在“esac”后面?

嵌套案例 - 为什么必须“;;”放在可能的命令后面而不是直接放在“esac”后面?

我想要有关;;嵌套 case 语句中终止的解释。

它记录在某处吗?

为什么它不能像这样工作:

     #!/bin/ksh  
     ...    
     esac
     ;; 
     print "why here?"
     ...

但工作原理如下:

#!/bin/ksh

var1="C" 
var2=0

case ${var1} in
  A) print "A"  
  ;;

  B) print "B"
  ;;

  C) print "C"

     case $var2 in
       0)
         print "A B"
         ;;
       1)
         print "C"           
         ;;
     esac
     print "why here?"
     ;;  

  *) print ${var1}
  ;;
esac

答案1

;;分隔 case 块。那么 shell 期望在它之后找到的是另一个图案开始一个新的 case 块,或esac标记case语句的结束。print something不是esac且不是有效的图案,所以你会得到一个错误。如果你想要一个默认/倒退case 块,使用*)(*)

case $something in
  (foo) cmd1
        cmd2
        ;; # end of first block
  (bar) cmd3;; # end of second block
  (*)   cmd4 # default case block
esac # note that the ;; is not required before the esac.

语句是否case嵌套与此无关。

答案2

在我看来,Bash 的手册页中有详细记录:

摘抄

   case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
        A case command first expands word, and tries to match it against 
        each pattern in turn, using the same matching rules as for 
        pathname expansion  (see Pathname Expansion below).  The word is 
        expanded using tilde expansion, parameter and variable expansion, 
        arithmetic substitution, command substitution, process substitution 
        and quote removal.  Each pattern examined is expanded  using  tilde  
        expansion,  parameter  and  variable  expansion,  arithmetic  
        substitution, command substitution, and process substitution.  If 
        the shell option nocasematch is enabled, the match is performed 
        without regard to the case of alphabetic characters.  When a match  
        is  found, the  corresponding list is executed.  

        If the ;; operator is used, no subsequent matches are attempted 
        after the first pattern match. Using ;& in place of ;; causes 
        execution to continue with the list associated with the next set of 
        patterns.  Using ;;& in place  of ;;  causes  the shell to test the 
        next pattern list in the statement, if any, and execute any 
        associated list on a successful match. The exit status is zero if no 
        pattern matches.  Otherwise, it is the exit status of the last 
        command executed in list.

这不起作用,因为;;符号位于 case ... esac 块之外。

 esac
 ;; 
 print "why here?"

另外,您的示例显示了 Korn shell ( ksh),但符号与我所了解的相同ksh。它也显示在这里:

参考

相关内容