Linux Bash Case Statement with Examples

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 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.





  • EXPRESSION is the value we want to evaluate.
  • PATTERN1 one of the situation we want to check
  • PATTERN2 is another situation we want to check
  • ... means we can add more situations like PATTERN1 and PATTERN2 .
  • STATEMENTS is the code we want to execute when the situation meets.
  • esac is the end of case 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.


case $(whoami) in 
               echo "You are ismail" ;; 
               echo "You are root" ;; 
Check Current User Example
Check Current User Example

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" 

read userage 

case $userage in 
               echo "You are 18 years old" ;; 
               echo "You are 20 years old" ;; 
Check Given Input
Check Given Input

LEARN MORE  Ternary Operator In Java Tutorial with Examples

Leave a Comment