Bash Case
In this Bash Tutorial, we shall learn the syntax and usage of Bash Case statement with example Bash Scripts.
Bash Case if similar to switch case in other programming lanugages.
Syntax of Bash Case
Syntax of Case statement in Bash Shell Scripting is as shown below :
case EXPRESSION in
CASE1)
COMMAND-LIST
;;
CASE2)
COMMAND-LIST
;;
CASEN)
COMMAND-LIST
;;
esac
where
EXPRESSION | where expression evaluates to a value. |
CASEN | One of the value the expression could evaluate to. |
COMMAND-LIST | Set of commands to be run when a CASE matches. |
Note : Providing * for a case can make the case to match to any value. This can be used as a default case when used as a last case.
Example 1 : Bash-Case Statement
In this example, we shall look into a simple scenario to illustrate case statement.
#!/bin/bash
time=12
# if condition is true
case $time in
9)
echo Good Morning!
;;
12)
echo Good Noon!
;;
17)
echo Good Evening!
;;
21)
echo Good Night!
;;
esac
~$ ./bash-case-example
Good Noon!
In the above example, the expression matches with second case 12 and therefore the commands for the corresponding case got executed.
Example 2 : Bash-Case statement with Default Case
In this example, we shall look into a scenario where there is a default case when no previous cases has a match.
#!/bin/bash
time=15
# if condition is true
case $time in
9)
echo Good Morning!
;;
12)
echo Good Noon!
;;
17)
echo Good Evening!
;;
21)
echo Good Night!
;;
*)
echo Good Day!
;;
esac
~$ ./bash-case-default-example
Good Day!
The expression, does not match to any of the cases but last, default case.
Conclusion
In this Bash Scripting Tutorial, we have learnt about the syntax of usage of Bash Case statement with example bash scripts.