Shell case statement
The case statement is equivalent to a multi-branch if/elif/else statement, and using case makes the script look simpler and neat. In the case statement, the program compares the obtained values with the conditions in the case expression one by one, executes the corresponding statement if it matches, and stops execution when it encounters a double semicolon (;;). If no match is found, execute the statement that follows *), which is equivalent to the default function in other languages.
Basic grammar
Case "var" in
Value 1)
Statement
Value 2)
Statement
Value n)
Statement
*)
Statement
Esac
The last branch statement, that is, before esac, can omit the double semicolon
Case example
[root@localhost Test] # cat case.sh
#! / bin/bash
Astatine 1
Case "${a}" in
1)
Echo "input number is 1"
2)
Echo "input number is 2"
3)
Echo "input number is 3"
*)
Echo "case default value"
Esac
[root@localhost Test] # bash case.sh 1
Input number is 1 # matching condition 1
[root@localhost Test] # bash case.sh 3
Input number is 3 # matching condition 3
[root@localhost Test] # bash case.sh a
Case default value # does not match the condition
The same effect can be achieved by using if statements.
[root@localhost Test] # cat caseif.sh
#! / bin/bash
Astatine 1
If [${a}-eq 1]
Then
Echo "input number is 1"
Elif [${a}-eq 2]
Then
Echo "input number is 2"
Elif [${a}-eq 3]
Then
Echo "input number is 3"
Else
Echo "case default value"
Fi
[root@localhost Test] # bash caseif.sh 1
Input number is 1
[root@localhost Test] # bash caseif.sh 3
Input number is 3
[root@localhost Test] # bash caseif.sh a
Caseif.sh: line 3: [: a: expect an integer expression
Caseif.sh: line 6: [: a: expect an integer expression
Caseif.sh: line 9: [: a: expect an integer expression
Case default value
Summary of case statements
1. The case statement is more suitable for a fixed set of numbers or strings with fewer variables.
2. Case is often used to write startup scripts for services, etc.
3. If takes values for judgment and comparison, and its application is wider than that of case, and most case statements can be replaced by if.