Case ... Esac is similar to the switch ... case statement in other languages, and is a multi-branch selection structure.
The case statement matches a value or a pattern, and if the match succeeds, the matching command is executed. The case statement is in the following format:
Case inch mode 1) Command1 command2 command3 ; Mode 2) Command1 command2 command3 ;; *) Command1 command2 command3 ;; Esac
The case works as shown above. The value must be followed by the keyword in, and each pattern must end with a closing parenthesis. The value can be either a variable or a constant. The matching discovery value conforms to a pattern, in which all commands begin to execute until;;.;; Similar to break in other languages, it means jumping to the end of the entire case statement.
The value will detect each pattern that matches. Once the pattern matches, the other mode is no longer resumed after the corresponding command is executed. If there is no matching pattern, use an asterisk * to capture the value and then execute the subsequent command.
The following script prompts you to enter 1 to 4 to match each pattern:
#!/bin/BashEcho 'Input A number between 1 to 4'Echo-E'Your number is:\c'Read Anum Case$aNuminch 1)Echo 'You select 1' ;; 2)Echo 'You select 2' ;; 3)Echo 'You select 3' ;; 4)Echo 'You Select 4' ;; *)Echo 'You does not select a number between 1 to 4' ;;Esac:<<EOF I just want to think about Java, if it's 1, do 1 2, but no. Case$aNuminch 1)Echo 'You select 1' 2)Echo 'You select 2' ;; 3)Echo 'You select 3' ;; 4)Echo 'You Select 4' ;; *)Echo 'You does not select a number between 1 to 4' ;;EsacEOF
Enter different content, there will be different results, for example:
1 4 Your number is: 3 Select3
One more example:
#!/bin/bashoption="${1}" Case${option}inch-f) file="${2}" Echo "File name is $FILE" ;; -D) dir="${2}" Echo "Dir name is $DIR" ;; *) Echo "$ (basename ${0}): Usage: [-f file] | [-D directory]"Exit1#Command to come out of the program with status1Esac
Operation Result:
[Email protected] shell]# bash case2. SH Case2. SH file] | [-D directory][[email protected] shell]# bash case2. SH -F index.htmlfile name is index.html[[email protected] shell]# bash case2. SH -d unixdir name is UNIX
Shell Case ESAC Statement