The Wayback Machine - https://web.archive.org/web/20230321154150/https://www.geeksforgeeks.org/bash-scripting-case-statement/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Bash Scripting – Case Statement

Improve Article
Save Article
  • Last Updated : 31 May, 2022
Improve Article
Save Article

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 statement has an edge over if-statements because it improves the readability of our code and they are easier to be maintained. Case statements in a Bash script are quite similar to Case statements in C language. But unlike C, 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
  • A case statement begins with the case keyword which is followed by an expression and the in the keyword.
  • It ends with the esac keyword.
  • Multiple pattern cases can be used separated by | operator.
  • Closing parenthesis operator ‘)’ is used to end the pattern cases list.
  • A pattern case can contain special characters.
  • A pattern case and its body are termed as a clause.
  • Pattern case body must be followed by ;;.
  • In case an expression matches with two patterns cases then in such case the body corresponding to the first matching pattern case that matches the expression is executed.
  • 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.
  • 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.

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.

5. Run the script.

./department.sh

Output:

Output a Description for Each Option

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.

5. Run the script.

./department.sh

Output:

Using Multiple Patterns cases

3. Save the script.

5. Run the script.

./department.sh

Example 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 expressions that are 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.

5. Run the script.

./department.sh

Output:

 for Loops

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:

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

5. Run the script using the below command.

./student.sh

Output:

Prompt User with Yes or No

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

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!