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
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.
case $(whoami) in
echo "You are ismail" ;;
echo "You are root" ;;
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.
echo "Input Your Age"
case $userage in
echo "You are 18 years old" ;;
echo "You are 20 years old" ;;