Shell Study 16 - Shell case esac statement

case ... esac is similar to switch ... case statements in other languages ​​and is a multi-branch selection construct.
A case statement matches a value or a pattern, and if the match succeeds, executes the matching command. The format of the case statement is as follows:
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 be terminated with a closing parenthesis. The value can be a variable or a constant. After the match finds that the value matches a certain pattern, all commands during the period start to be executed until ;;. ;; Similar to break in other languages, it means to jump to the end of the entire case statement.
The value will detect every pattern that matches. Once the pattern is matched, no other patterns will be continued after the corresponding command of the matched pattern is executed. If there is no matching pattern, use the asterisk * to capture the value, and then execute the following command.
The following script prompts for 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 'You 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
Another 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.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325683514&siteId=291194637