The bash case
statement can be used when you have multiple choices conditions. Using bash case
statement, it will be more readable and easier to maintain instead of nested if statements. This tutorial shows you the basics and use of the Bash case statement
in shell scripts.
The Bash case
statement has a similar concept with the JavaScript or C switch statement. The main difference is that unlike the C switch statement, the Bash case
statement doesn’t continue to search for a pattern match once it has found one and executed statements associated with that pattern.
case Statement Syntax
Below is the basic syntax for the Bash case statement
:
case EXPRESSION in
PATTERN_1)
STATEMENTS
;;
PATTERN_2)
STATEMENTS
;;
PATTERN_N)
STATEMENTS
;;
*)
STATEMENTS
;;
esac
Following are the some key points which need to keep in mind while using bash case
statement.
- The
case
statement starts with the case keyword and ends with theesac
keyword. - To use the multiple patterns separate by the
|
operator. The)
operator terminates a pattern list. - A pattern can have special characters.
- A pattern and its associated commands are known as a clause.
- It must terminate the each clause with
;;
. - The commands corresponding to the first pattern that matches the expression will execute.
- Use the wildcard asterisk symbol (
*
) for the final pattern for the default case. It will always match. - When there is no pattern matched, it returns status zero. Otherwise, the return status is the exit status of the executed commands.
Case Statement Example
Below is the example to print the official language of a given country using the case
statement in bash script:
#!/bin/bash
echo -n "Enter the name of a country: "
read COUNTRY
echo -n "The official language of $COUNTRY is "
case $COUNTRY in
Lithuania)
echo -n "Lithuanian"
;;
Romania | Moldova)
echo -n "Romanian"
;;
Italy | "San Marino" | Switzerland | "Vatican City")
echo -n "Italian"
;;
*)
echo -n "unknown"
;;
esac
Save the file and run it from the command line.
bash languages.sh
Once you run the script it will ask you to enter the country name. If you will enter the “Lithuania”, it will match the first pattern, and the echo command in that clause will be executed.
It will display the following output:
Enter the name of a country: Lithuania
The official language of Lithuania is Lithuanian
If the entered country doesn’t match with any other then script will execute the echo
command inside the default clause.
Enter the name of a country: India
The official language of India is unknown
Conclusion
You learned how to use the case
statement while writing the bash script.
If you have any question or feedback, please leave a comment below.