The Shell Case statement is a multi-select statement. A case statement can be used to match a value with a pattern, and if the match succeeds, the matching command is executed. The case statement is in the following format:
The code is as follows:
Case value in
Mode 1)
Command1
Command2
...
CommandN
;;
Mode 2)
Command1
Command2
...
CommandN
;;
Esac
The case works as shown above. The value must be followed by the word in, and each pattern must end with a closing parenthesis. The value can be either a variable or a constant. After the match discovery value conforms to a pattern, all commands begin to execute until;;.
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:
The code is as follows:
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 4
Your number Is:3
you select 3
Read Select
Case $select in
1)
echo "Do Open file operation"
2)
echo "Do display a file operation"
3)
echo "Do edit a file operation"
4)
echo "Do delete a file operation"
*)
echo "There is nothing to do!"
Exit 1
Esac
Shell's case statement