Conditional Structures: Case Construct
Case construct in Bash
| Case |
| • Used to execute statements based on specific values.
• Often used in place of an if statement if there are a large number of conditions. |
| • The value used can be an expression.
• Each set of statements must be ended by a pair of semicolons. • *) is used to accept any value not matched with a list of values. |
| case $var in
val1) statements;; val2) statements;; *) statements;; esac |
| Example | |
| Script | Output |
| #!/bin/bash
var=2 case $var in [0-5] ) echo The value is between 0 and 5 ;; [6-9] ) echo The value is between 6 and 9 ;; *) echo It’s something else… esac
exit |
The value is between 0 and 5
Remark: The special form [0-5] is used to define a range of values between 0 and 5 inclusive. |
| Script | Output |
| #!/bin/bash
char=f case $char in [a-zA-z] ) echo An upper or lower case character ;; [0-9] ) echo A number ;; * ) echo Something else ;; esac
exit |
An upper or lower case character
Remark: The case construct can be used to test characters as well. Also shown is the concatenation of ranges, here [a-zA-z] tests for all alphabetic characters, both lower- and uppercase. |

| Example | |
| Script | Output |
| #!/bin/bash
name=Tim case $name in Dan ) echo It’s Dan. ;; Marc | Tim ) echo It’s me. ;; Ronald ) echo It’s Ronald. ;; * ) echo I don’t know you. ;; esac Exit |
It’s me.
Remark: Finally, strings can also be tested with the name is Marc or Tim, then the test is satisfied. We use the logical OR operator in this case, which is legal within the case test construct. |
