How To Use Bash Case Statement?

The Linux bash provides case statement in order to create conditionals where one of the multiple choices can be selected according to the specified condition. Event there is the if statement the case statement provides more readability and is easy to use.

The case statement is very similar to the popular programming languages provide switch..case statements. Programming languages like C, C++, Java, PHP, Python, C# provide the switch..case statements. In this tutorial, we will learn how to use the bash switch case.

case Statement Syntax

The case statement syntax is like below.

case EXPRESSION in
   PATTERN1)
   STATEMENTS
   ;;

   PATTERN2)
   STATEMENTS
   ;;

   ...

   *)
   STATEMENTS
   ;;
esac
  • PATTERN1, PATTERN2 are the conditions which can meth by the specified EXPRESSION
  • STATEMENTS are the statements which will be executed when the related PATTERN is matched.
  • *) condition is used for default condition where non of the PATTERN is matched.
  • esac specifies the end of the case statement.

Single Case Example

In this part we will make a simple case statement example where we will only check a single condition if it is true or not. If the specified condition is true a specific script block is executed.

#!/bin/bash

echo -n "Enter your name:"

read NAME

case $NAME in

   ismail)
      echo "Name is ismail"
      ;;

esac

Multiple Case Example

The case statement can be used with multiple conditions where the matched condition statements are executed. In the following example, we read the NAME and check for multiple conditions.

#!/bin/bash

echo -n "Enter your name:"

read NAME

case $NAME in

   ismail)
      echo "Name is ismail"
      ;;

   ahmet)
      echo "Name is ahmet"
      ;;

   elif)
      echo "Name is elif"
      ;;

esac

Default Case

The case statement also provides the default case where if none of the conditions are matched the default case is executed. The default case is expressed with the *) .

#!/bin/bash

echo -n "Enter your name:"

read NAME

case $NAME in

   ismail)
      echo "Name is ismail"
      ;;

   ahmet)
      echo "Name is ahmet"
      ;;

   elif)
      echo "Name is elif"
      ;;

esac

Leave a Comment