In bash scripting, decision-making plays a crucial role in controlling the flow of your script. The case esac statement provides an efficient and concise way to perform multiple conditional checks in bash scripting. In this tutorial, we’ll explore how to use the case esac statement for decision making, along with some practical examples.

Syntax

The case...esac is similar to if..elif..else statements with multiple conditions.

 1case $variable in
 2    pattern1)
 3        # code block executed if variable matches pattern1
 4        ;;
 5    pattern2)
 6        # code block executed if variable matches pattern2
 7        ;;
 8    patternN)
 9        # code block executed if variable matches patternN
10        ;;
11    *)
12        # code block executed if none of the patterns match
13        ;;
14esac

Grade assigner Example

In this example, like programming language, we are asked for marks and when we provide marks, we get back grades.

 1#!/bin/bash
 2
 3echo "Enter your marks out of 100."
 4read marks
 5
 6case $marks in
 7    [0-6]*)
 8        echo "Marks below 60%. You've got C."
 9        ;;
10    7[0-9]*)
11        echo "Marks between 70% and 79%. You've got B."
12        ;;
13    8[0-9]*|9[0-9]*|100)
14        echo "Marks above or equal to 80%. You've got A!!!"
15        ;;
16    *)
17        echo "Invalid input entered."
18        ;;
19esac

Output:

bash script.sh
Enter your marks out of 100.
78
Marks between 70% and 79%. You've got B

Example of working with system services

In below example, we prompt the user to select a system service by entering a number. Based on the selected number, we will execute corresponding commands.

 1#!/bin/bash
 2
 3echo "Please select a system service: "
 4echo "1. Apache"
 5echo "2. MySQL"
 6echo "3. Nginx"
 7 
 8read -p "Enter your choice to start: " choice
 9 
10case $choice in
11    1)
12        echo "Starting Apache..."
13        # code for starting Apache
14        ;;
15    2)
16        echo "Starting MySQL..."
17        # code for starting MySQL
18        ;;
19    3)
20        echo "Starting Nginx..."
21         # code for starting Nginx 
22esac

This script prompts the user to select a system service by entering a number. Based on the user’s input, it executes corresponding commands to start the chosen service.