Case Statement
The case statement can be used to compare a single value to a set of other values. It can not handle the concept of greater than or less then.
When pattern matching, an asterisk (*) means zero or more characters, brackets [ ] can be used to denote character sets, and a single pipe ( | )can be used as an “or”, and a question mark (?) denotes a single character.
case Statement Syntax
case Execution Steps
- The value of the variable is compared to the first test condition.
- If the variable matches the test condition,
- the code is executed
- and you are done.
- If the variable does not match the test condition, the value of the variable is compared to the next test condition.
- Repeat steps 2 and 3 until either a match is found or all the conditions are tested.
- If no test condition is matched, the code with the *) condition is executed.
Special Contructs && and ||
The constructs && and || are a short hand form of the if command, but should be used sparingly.
Example 1:
- command1 && command2
- If command1 returns an exit status of 0, then execute command2
Example 2:
- command1 || command3
- If command1 returns a non-zero exit status, then execute command3
Example 3:
- command1 && command2 || command3
- If command1 returns a 0 exit status, then execute command2 else execute command3