In this topic, we will discuss the basics of case statements and how to use them in Bash scripts.
The Bash case statement is the simplest form of IF-THEN-ELSE with many ELIF elements. Using the case statement makes our bash script more readable and easier to maintain. These are generally applied to simplify the complex conditions having multiple different choices.
Case Statement Syntax
Syntax of the bash case statement is given below:
There are some key points of bash case statements:
How it works
First of all, the case statement expands the expression and tries to match with each of the included patterns. When it finds a match, all the linked statements are executed till the double semicolon (;;). After the first match, case terminates with the exit status of the last executed statement.
If there is no matched pattern, the exit status of the case is zero. Otherwise, the return status is the exit status of the executed statements.
If the default asterisk pattern is used, it will be executed in case of no matched pattern.
Let's try to understand this mechanism with the help of a few examples:
In this example, we have defined a simple scenario to demonstrate the use of the case statement.
In this example, we have defined a combined scenario where there is also a default case when no previous matched case is found.
We have run the script with three different inputs, check out the output below:
ConclusionIn this topic, we have learned about the syntax and usage of Bash Case statement with the examples.