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.
- The Bash case statement takes a value once and tests that value multiple times. It stops searching for a pattern once it has found it and executed the statement linked with it, which is almost opposite in case of the C switch statement.
Case Statement Syntax
Syntax of the bash case statement is given below:
There are some key points of bash case statements:
- Each case statement in bash starts with the ‘case’ keyword, followed by the case expression and ‘in’ keyword. The case statement is closed by ‘esac’ keyword.
- We can apply multiple patterns separated by | operator. The ) operator indicates the termination of a pattern list.
- A pattern containing the statements is referred to as a clause, and it must be terminated by double semicolon (;;).
- An asterisk symbol (*) is used as a final pattern to define the default case. It is used as a default case when used as the last case.
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:
In this topic, we have learned about the syntax and usage of Bash Case statement with the examples.