case statement (chooses from multiple processing paths)
- Organization of this page
Format
case expression in pattern-1)processing-a ;; pattern-2)processing-b ;; ... *)processing-x ;; esac
Summary
This control statement determines the processing to be executed, based on finding a match with a specified character string (expression).
Description
The in keyword indicates the beginning of the types of processing defined in the case statement, and esac indicates the end of the case statement. When the specified expression matches a specified pattern, the processing described between the right parenthesis ()) and the double semicolons (;;) is executed. Multiple patterns can be specified, with the double semicolons (;;) serving as the delimiter between patterns. The pattern specified as an asterisk (*) is for the default processing when no match is detected with any of the other patterns. The matching of expression to the patterns is conducted in the order in which the patterns are specified. If expression matches multiple patterns, the processing prescribed for the first match is executed.
You can specify a left curly bracket ({) instead of in, and you can specify a right curly bracket (}) instead of esac. If you use in, you must also use esac; if you use {, you must also use }. If these specifications are not paired in this way, the syntax will be invalid and the control statement will terminate with an error.
A regular expression with wildcards can be specified in pattern.
Usage examples
-
The ;; indicating the end of a pattern can be specified on the same line as the processing.
case $cnt in 0) echo "cnt is ZERO" ;; *) echo "cnt is not ZERO" ;; esac
-
If the last command in a pattern is an extended script command, add a linefeed to prevent ;; from being interpreted as an argument of the extended script command.
case $cnt in 0) #-adsh_step_start STEP01 echo "cnt is ZERO" #-adsh_step_end ;; <--Error. Specify linefeed before ;;. *) #-adsh_step_start STEP01 echo "cnt is not ZERO" #-adsh_step_end ;; esac