Home Bash scripting Bash Scripting – Case Statement

Bash Scripting – Case Statement

Bash case statement examples | How to use case statement in Bash scripts

By Karthick
Published: Last Updated on 1,174 Views

In the previous article, we have seen how to work with conditional statements in bash to evaluate conditions and take decisions based on the results. Similarly, in this article, we will learn how to use case statement in Bash scripts, which is also used to evaluate conditions. You can use a Bash case statement instead of writing a long list of if..elif..else statement. If you have no idea about conditional statements, we have a detailed article on the topic. I suggest you take a look at it before reading this article.

Case statement syntax

The syntax of case statement in bash is given below:

case expression in
  pattern1) STATEMENTS ;;
  pattern2) STATEMENTS ;;
  Pattern3 | Pattern4 | pattern5) STATEMENTS ;;
  pattern-N) STATEMENTS ;;
  *) STATEMENTS ;;
esac

Explanation:

  1. The keyword "case" and "esac" marks the start and end of the case statement.
  2. The keyword case should be followed by an "expression". This expression will be evaluated and the output will be searched against the list of patterns.
  3. After the expression, the "in" keyword should be written, which points to "value in patterns".
  4. You can create as many patterns as you want. You can think of each pattern as an if and elif clause in the conditional statement. If the value evaluated from the expression is matched against a pattern, that pattern will run its block of code. The remaining patterns will be skipped.
  5. Each statement inside the pattern should be terminated with a double semicolon (;;).
  6. Similar to the else clause in the if statement, in case statement there is a default pattern called asterisks (*) which will run its block of code if none of the patterns are matched.

Example 1 - Calculator using case statement

In this example, I have created a simple calculator using a case statement. Let me explain what happens when you run this code.

  1. The user is prompted to enter two numbers and it is stored in variables "X" and "Y".
  2. The user is prompted to enter the type of operation(add, subtract, multiply, divide) and stored in the variable "OPERATOR".
  3. In case statement the variable "OPERATOR" is evaluated and different patterns (+,-,x,/,%) are created for different operations.
  4. If a pattern is matched the particular pattern will run its statement skipping all other patterns in the case statement.
  5. If you try to enter any other values other than the desired arithmetic operators then the default pattern (*) will run its statement.
#!/usr/bin/env bash

read -p "Enter the first number(X)  :  " X
read -p "Enter the second number(Y) :  " Y
read -p "
Addition => +
Subtract => -
Multiply => x
Division => /
Reminder => %

Choose any one operator   :  " OPERATOR
case "$OPERATOR" in
 +)
   echo -e "\nAddition of X and Y is $(( X + Y ))" ;;
 -)
   echo -e "\nSubtraction of X and Y is $(( X - Y ))" ;;
 x)
   echo -e "\nMultiply X and Y is $(( X * Y ))" ;;
 /)
   echo -e "\nDivision of X and Y is $(( X / Y ))" ;;
 %)
   echo -e "\nReminder of X and Y is $(( X % Y ))" ;;
 *)
   echo -e "\n[ERROR] You have chosen an operator that is not in the list.
You can choose either(+, -, x, /, %) operator from the list.
Rerun the program again."
esac

Take a look at the below image, I am submitting the code and choosing the "Addition Operator".

Addition operator
Addition operator

I am running the same code again but this time giving a random value which will make the default pattern (*) run its statement.

Default pattern
Default pattern

Example 2 - Creating multiple patterns in single clause

In the previous example, we have created different patterns for different arithmetic operators. It is also possible to create multiple patterns in the same clause and if any of the patterns are matched the particular statement will run. The syntax will be the same but you will add a pipe symbol (|) and add different patterns in the same line like below.

case expression in
   Pattern1 | Pattern2 | pattern3) 
   STATEMENTS ;;
   *)
   STATEMENTS ;;
esac

In the below example, the user will enter the year as input and will get the orange cap details from IPL data. In the years 2015, 2017, and 2019 same player won the orange cap so I have created a different year as the pattern in the same clause.

read -p "Choose the year between 2015 - 2021 to get orange cap player name: " CAP
case "$CAP" in
 2015 | 2017 | 2019)
   echo -e "\nOrange cap winner for $YEAR is David Warner" ;;
 2016)
   echo -e "\nOrange cap winner for $YEAR is Virat Kohli" ;;
 2018)
  echo -e "\nOrange cap winner for $YEAR is Kane Williamson" ;;
 2020)
   echo -e "\nOrange cap winner for $YEAR is KL Rahul" ;;
 2021)
   echo -e "\nOrange cap winner for $YEAR is Ruturaj Gaikwad" ;;
 *)
   echo -e "\n[ERROR] Enter the year between 2015 - 2021."
esac
Multiple patterns in the same clause
Multiple patterns in the same clause

Example 3 - Pattern matching in case statement

Pattern matching can be used in case statements. I am using the same example from the previous section but adding an extra pattern (20[2-9][2-9]) where if the user enters any year above 2021 it will print a message saying "series yet to happen".

read -p "Choose the year between 2015 - 2021 to get orange cap player name: " CAP
case "$CAP" in
 2015 | 2017 | 2019)
   echo -e "\nOrange cap winner for $YEAR is David Warner" ;;
 2016)
   echo -e "\nOrange cap winner for $YEAR is Virat Kohli" ;;
 2018)
  echo -e "\nOrange cap winner for $YEAR is Kane Williamson" ;;
 2020)
   echo -e "\nOrange cap winner for $YEAR is KL Rahul" ;;
 2021)
   echo -e "\nOrange cap winner for $YEAR is Ruturaj Gaikwad" ;;
 20[2-9][2-9])
   echo -e "\nSeries is yet to happen for the year $CAP" ;;
 *)
   echo -e "\n[ERROR] Enter the year between 2015 - 2021."
esac
Case statement with pattern matching
Case statement with pattern matching

Example 4 - Get user confirmation

Sometimes you may require the user to provide confirmation to proceed to the next step in your program. Using a case statement would be a good choice for this use case.

In the previous example, pattern is written in one line and statements in another line but you can also write patterns and statements in a single line like as shown below.

read -p "Input file is received in CSV format, Please confirm to load the data into production database  : " CONFIRM
case "$CONFIRM" in
 [Yy] | [Yy][Ee][Ss] ) echo "++ Running the utility to load the data to the database.." ;;
 [Nn] | [Nn][Oo] ) echo -e "++ Skipping load db step upon user confirmation..\n Exiting the script.." ;;
 *) echo -e "[ERROR] = Wrong Input, Exiting the script.."
esac
User confirmation using case statement
User confirmation using case statement

Example 5 - Case statement with return codes

You can write logic to capture the return code of the previously run command and take some actions using case statements. I am creating a GUI dialog box to accept the user name and password from the user using zenity. If the user submits the username and password successfully, zenity will throw the return code as zero and based on it I have added logic to add a new user. Anything other than zero, an error message will be thrown.

INFO=$(zenity --password --username)
case $? in
 0)
   USERNAME=$(echo ${INFO} | awk -F "|" '{ print $1 }')
   PASSWORD=$(echo ${INFO} | awk -F "|" '{ print $2 }')
   useradd -m -p "${PASSWORD}" "${USERNAME}"
   ;;
 *)
   echo "[ERROR] - User not added."
esac
User creation script
User creation script

I have pressed the "Cancel" button in the dialog box, so it has thrown me an error using default pattern (*).

Cancelled the dialog box
Cancelled the dialog box

Reference scripts

To get more comfortable with case statements, you can look at existing codes written using case statements. A better place to start would be to read startup scripts under /etc/init.d directory. For example, I have virtualbox installed in my machine and it has a startup file under /etc/init.d directory. There is a section of code that is written using a case statement which will give a good idea of how the case statement works.

$ cd /etc/init.d/
$ cat bluetooth
Startup scripts
Startup scripts

Conclusion

In this article, we have seen what is case statement in Bash and different ways to use it. Both conditional statement and case statement serve the same purpose. You should have a better understanding of which method fits the use case. Case statements will also be used when you have to create help functions using getopt and getopts programs. Create a script and start practicing the examples we have given here to understand more about case statements.

You May Also Like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More