case statement

The case statement is often used when more than two outcomes are possible. Here is the syntax:

case $VARIABLE in
value_1) commands for specified value_1 ;;
value_2) commands for specified value_2 ;;
value_3) commands for specified value_3 ;;
*) commands for value not matching any specified choices ;;
esac

The $VARIABLE is compared against the values until a match is found. If a match is found, the associated commands are executed and the case statement is terminated. If the value the user enters doesn’t match any of the choices specified in the case statement, the *) characters start the code portion that runs in this situation. esac indicates the end of the case statement.

Consider the following example.

#!/bin/bash

echo “Select your choice:”
echo “Press 1 to display your current directory”
echo “Press 2 to display the current date and time”
echo “Press 3 to list the content of the current directory”
read CHOICE
case $CHOICE in
1) pwd;;
2) date;;
3) ls -l;;
*) echo Invalid selection;;
esac

In the example above, you can see that the user can select whether he/she wants to display the current directory, the current time, or list the directory content. If the user enters a value that doesn’t equal 1, 2, or 3, the Invalid selection message will be displayed:

linux case statement

The case statements are called switch statements or multiway branches in other programming languages.
Geek University 2022