Open In App

Bash Scripting – Case Statement

Last Updated : 15 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A case statement in bash scripts is used when a decision has to be made against multiple choices. In other words, it is useful when an expression has the possibility to have multiple values. This methodology can be seen as a replacement for multiple if-statements in a script. Case statements have an edge over if-statements because it improves the readability of our code and they are easier to maintain. Case statements in a Bash script are quite similar to Case statements in C language. But unlike C, the Bash Case statement stops continuing the search as soon as the match occurs. In simple words, they don’t require any break statement that is mandatory to be used in C to stop searching for a pattern further. 

The basic syntax of a case statement is given below,

Syntax:

case EXPRESSION in
  Pattern_Case_1)
   STATEMENTS
   ;;
 Pattern_Case_1)
   STATEMENTS
   ;;
 Pattern_Case_N)
   STATEMENTS
   ;;
 *)
   STATEMENTS
   ;;
esac

Here’s how the case statement works:

  • EXPRESSION is the variable or value that is evaluated against different patterns (cases) to find a match.
  • The case statement starts with the keyword case followed by the EXPRESSION to be evaluated.
  • Each case is defined by a Pattern_Case that represents a specific value or pattern to be compared with the EXPRESSION.
  • After each Pattern_Case, there are statements to be executed if the EXPRESSION matches the specific Pattern_Case. These statements are denoted by STATEMENTS.
  • The ;; at the end of each STATEMENTS block indicates the end of a case block.
  • The *) is a special case known as the “default” case. If none of the previous patterns match the EXPRESSION, the STATEMENTS under the *) block will be executed.
  • The esac keyword marks the end of the case statement.
  • In case no pattern is matched, the return status is zero. Otherwise, the return status is the exit status of the executed body of the matched pattern case.
  • Like C provides default keyword for default statement, likewise in the Bash case statement, we can use the wildcard asterisk symbol (*) and define a final pattern case to define the default case.

Example 1: Output a Description for Each Option

In this example a script allows the user to select a department and shows a description corresponding to the input with the help of an echo command. In this script, we have assigned the DEPARTMENT variable as “Computer Science”. Thus, the body of the first pattern case gets executed. 

You can follow the instructions given below:

1. Open the terminal (Ctrl + Alt + T) and create the script:

department.sh

2. Add these statements to the script:

#!/bin/bash


DEPARTMENT="Computer Science"

echo -n "Your DEPARTMENT is "

case $DEPARTMENT in

  "Computer Science")
    echo -n "Computer Science"
    ;;

   "Electrical and Electronics Engineering" | "Electrical Engineering")
    echo -n "Electrical and Electronics Engineering or Electrical Engineering"
    ;;

  "Information Technology" | "Electronics and Communication")
    echo -n "Information Technology or Electronics and Communication"
    ;;

  *)
    echo -n "Invalid"
    ;;
esac

3. Each of the lines is described below:

  • The first line in the script starts with the shebang (#!).
  • It instructs the operating system to use a particular interpreter to parse the script.
  • We have initialized a DEPARTMENT variable as “Computer Science”.
  • Now, we are using a case statement.
  • Each expression has been handled through the case statement.
  • The last line, esac, has been used to terminate the case statement.

4. Save the script and make it executable.

chmod +x department.sh

5. Run the script.

./department.sh

Output:

406

Example 2: Using Multiple Patterns cases

In each clause, we can use multiple pattern cases. If the expression matches with at least one pattern case then the body gets executed of the clause. In this script, we have assigned the DEPARTMENT variable as “Electronics and Communication”. The third pattern case has two values separated by the pipe ( | ) operator. Thus, the body of the third pattern case gets executed.

You can follow the instructions given below:

1. Open the terminal (Ctrl + Alt + T) and create the script:

department.sh

2. Add these statements to the script:

#!/bin/bash

DEPARTMENT="Electronics and Communication"

echo -n "Your DEPARTMENT is "

case $DEPARTMENT in

  "Computer Science")
    echo -n "Computer Science"
    ;;

   "Electrical and Electronics Engineering" | "Electrical Engineering")
    echo -n "Electrical and Electronics Engineering or Electrical Engineering"
    ;;

  "Information Technology" | "Electronics and Communication")
    echo -n "Information Technology or Electronics and Communication"
    ;;

  *)
    echo -n "Invalid"
    ;;
esac

3. Each of the lines has been discussed below:

  • The first line in the script starts with the shebang (#!).
  • It instructs the operating system to use a particular interpreter to parse the script.
  • We have initialized a DEPARTMENT variable as “Electronics and Communication”.
  • Now, we are using a case statement.
  • Each expression has been handled through the case statement.
  • The last line, esac, has been used to terminate the case statement.

4. Save the script and make it executable.

chmod +x department.sh

5. Run the script.

./department.sh

Output:

407Example 3: for Loops

In this script, we have assigned the department of three students of a class in an array DEPARTMENT. In other words, we are going to process more than one expression that is described in the DEPARTMENT variable. To iterate over multiple expressions, we can use a for a loop. 

You can follow the instructions given below:

1. Open the terminal (Ctrl + Alt + T) and create the script:

department.sh

2. Add these statements to the script:

#!/bin/bash

DEPARTMENT=("Electronics and Communication" "Computer Science" "Information Technology")

for value in "${DEPARTMENT[@]}"
do 
  case $value in
    "Computer Science")
      echo -n "Computer Science "
      ;;

    "Electrical and Electronics Engineering" | "Electrical Engineering")
      echo -n "Electrical and Electronics Engineering or Electrical Engineering "
      ;;

    "Information Technology" | "Electronics and Communication")
      echo -n "Information Technology or Electronics and Communication "
      ;;

    *)
      echo -n "Invalid "
      ;;
  esac
done

3. Each of the lines is described below:

  • The first line in the script starts with the shebang (#!).
  • It instructs the operating system to use a particular interpreter to parse the script.
  • We have initialized an array DEPARTMENT with three string literals.
  • Now, with the help of a for-loop, we are iterating over the array of elements.
  • Each expression has been handled through the case statement.
  • The last line, esac, has been used to terminate the case statement.

4. Save the script and make it executable.

chmod +x department.sh

5. Run the script.

./department.sh

Output:

408

Example 4: Prompt User with Yes or No

You can follow the instructions given below:

1. Open the terminal (Ctrl + Alt + T) and create the script:

department.sh

2. Add these statements to the script:

#!/bin/bash

echo -n "Are you a student? [yes or no]: "
read response
case $response in

        "Y" | "y" | "YES" | "Yes" | "yes")
                echo -n "Yes, I am a student."
                ;;

        "N" | "n" | "No" | "NO" | "no" | "nO")
                echo -n "No, I am not a student.";
                
                ;;
        *) echo -n "Invalid input"
            ;;
esac

3. Each of the lines is explained below:

  • The first line in the script starts with the shebang (#!).
    • It instructs the operating system to use a particular interpreter to parse the script.
  • The user is prompted as “Are you a student? [yes or no]”.
  • Now a response is given by the user through the keyboard.
  • The output of the response has been handled through a case statement.
  • The last line, esac, has been used to terminate the case statement.

4. Save the script and make it executable.

chmod +x department.sh

5. Run the script using the command below.

./department.sh

Output:

409

Example 5: Sending Signal to a Process

You can follow the instructions given below:

1. Open the terminal (Ctrl + Alt + T) and create the script:

signals.sh

2. Add these statements to the script:

#!/bin/bash

if [ $# -lt 2 ]
then
        echo "Usage : $0 Signalnumber PID"
        exit
fi

# Case statement
# Signal number (expression)
case "$1" in

1)  echo "Sending SIGHUP signal....."
    kill -SIGHUP $2
    ;;
2)  echo  "Sending SIGINT signal....."
    kill -SIGINT $2
    ;;
3)  echo  "Sending SIGQUIT signal....."
    kill -SIGQUIT $2
    ;;
4) echo  "Sending SIGKILL signals....."
   kill -SIGKILL $2
   ;;
*) echo "Signal number $1 has not been processed"
   ;;
esac

3. Each of the lines is explained below:

  • $1 is the signal number and $2 is the process id.
  • To pass or send a signal to the given process id we are using the kill command.
  • This will run the sleep command for a few seconds.
  • The body of the optional last comparison *) will be executed in the default case.

4. Save the script.

5. Run the script using the command below.

./signals.sh

Output:

$ sleep 10000

$ ps -a | grep sleep
23277 pts/2    00:00:00 sleep

$ ./signals.sh 9 31231
Sending SIGKILL signal

$ sleep 10000
Killed


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads