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.
Syntax
Syntax of 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
EXPRESSION
is the value we want to evaluate.PATTERN1
one of the situation we want to checkPATTERN2
is another situation we want to check...
means we can add more situations likePATTERN1
andPATTERN2
.STATEMENTS
is the code we want to execute when the situation meets.esac
is the end ofcase
statement.
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 "ismail")
and "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
