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 value in 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:
- Echo ' Input a number between 1 to 4 '
- echo ' Your number is:\c'
- Read Anum
- Case $aNum in
- 1) echo ' you select 1 '
- ;;
- 2) echo ' you select 2 '
- ;;
- 3) echo ' you select 3 '
- ;;
- 4) echo ' you select 4 '
- ;;
- *) echo ' Do not select a number between 1 to 4 '
- ;;
- Esac
Enter different content, there will be different results, for example:
Input a number between 1 to 4Your number Is:3you Select 3
One more example:
- #!/bin/bash
- Option="${1}"
- Case ${option} in
- - f) FILE="${2}"
- echo "File name is $FILE"
- ;;
- - D) DIR="${2}"
- echo "Dir name is $DIR"
- ;;
- *)
- echo "' BaseName ${0} ': Usage: [-f file] | [-D directory] "
- exit 1 # Command to come out of the program with status 1
- ;;
- Esac
Operation Result:
$./test.shtest.sh:usage: [-f filename] | [-D directory]$./test.sh-f index.htm$ vi test.sh$./TEST.SH-F index.htmfile name is index.htm$./test.sh-d unixdir N AME is unix$
Shell Script Learning 17 Shell Case ESAC statement