The bash case
statement is used to simplify complex conditionals in a bash script. Bash case
statements use a simple syntax that is often used instead of the if statement because it’s highly readable.
If you’ve worked with another programming language such as JavaScript, Java, or C, then the bash case statement will sound familiar. It works similar to the switch cases in C language and JavaScript, except the bash case stops after it finds a statement matching the pattern.
In this article, we will discuss the bash case statement along with its syntax and examples.
Bash Case Statement Syntax
The syntax for bash case statement is as follows:
case EXPRESSION in PATTERN_1 | PATTERN_2) STATEMENTS ;; PATTERN_3) STATEMENTS ;; *) STATEMENTS ;; esac
- Each case statement starts with the keyword
case
, followed by the case expression the keyword in, and ends with the keyword case spelled backwards, esac. - Each case statement can have multiple patterns (separated by an
|
) and each pattern list is terminated with)<strong>
. - A pattern and the commands associated with it are called clauses and each clause ends with an
;;
. - Using a wildcard character (
*
) as the final pattern in case statements is a best practice. - Case statements have two exit status:
- The command corresponding to the first matched pattern is executed.
- If no patterns match the case, then zero is returned.
Bash Case Statement Example
We will use bash case statements in the following example to print the capital of a country:
#! /bin/bash echo -n "Enter the name of a country:" read country echo -n "The capital of $country is: " case $country in Australia) echo -n "Canberra" ;; Egypt) echo -n "Cairo" ;; Ireland) echo -n "Dublin" ;; *) echo -n "unknown" ;; esac
The case statements start by asking and reading the name of a country from the user, and match the country with the list of patterns. Once it finds a match, it returns a statement with the name of the country and its capital. If the country name doesn’t match any of the patterns, then it returns unknown.
Bash Case Statement Use Cases
A few common use cases of the bash case statement are:
- Sending signals to a process.
- Startup script.
- Pattern matching in files.
- Find file type from its extension.
- Prompt users with a YES or NO.
Conclusion
We hope that you have a solid grasp over the bash case statements and its use cases. Case statements are often used to pass parameters to shell scripts from the command line and favored over the if statements because they make the scripts more readable.