Bash provides an interactive shell and programming environment for its users. Programming environment have very reach features like loops for and while, selection if and case. In this tutorial we will examine the
case mechanism in detail.
case statement is a bit different and complex then
if and other conditional expressions.
case statement generally uses
expression which is value we want to check and
patterns which is a case.
case EXPRESSION in PATTERN1) STATEMENTS ;; PATTERN2) STATEMENTS;; ... esac
EXPRESSIONis the value we want to evaluate.
PATTERN1one of the situation we want to check
PATTERN2is another situation we want to check
...means we can add more situations like
STATEMENTSis the code we want to execute when the situation meets.
esacis the end of
Check Current User Example
In this example we will check the current user and print the user name to the screen. In this example we will use
$(whoami) which will return current user name and check with
"root") conditions. If one of them matches we will print with
echo "You are ...";; line. Keep in mind that
;; specifies end of current condition.
#!/bin/bash case $(whoami) in "ismail") echo "You are ismail" ;; "root") echo "You are root" ;; esac
Check Given Input
We can get input from the user and use it in a case . In this example we will get current user age from command line as input and then print some sentence according to input age.
#!/bin/bash echo "Input Your Age" read userage case $userage in 18) echo "You are 18 years old" ;; 20) echo "You are 20 years old" ;; esac