Bash Case Statement

Bash Case Statement

In this tutorial, we will cover the basics of the Bash case statement and show you how to use it in your shell scripts.

The bash case statement is generally used to simplify complex conditionals when you have multiple different choices. Using the case statement instead of nested if statements will help you make your bash scripts more readable and easier to maintain.

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

The Bash case statement takes the following form:







  • Each case statement starts with the case keyword, followed by the case expression and the in keyword. The statement ends with the esac keyword.

  • You can use multiple patterns separated 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.

  • Each clause must be terminated with ;;.

  • The commands corresponding to the first pattern that matches the expression are executed.

  • It is a common practice to use the wildcard asterisk symbol (*) as a final pattern to define the default case. This pattern will always match.

  • If no pattern is matched, the return status is zero. Otherwise, the return status is the exit status of the executed commands.


Case Statement Example

Here is an example using the case statement in a bash script that will print the official language of a given country:

echo -n "Enter the name of a country: "

echo -n "The official language of $COUNTRY is "

case $COUNTRY in

    echo -n "Lithuanian"

  Romania | Moldova)
    echo -n "Romanian"

  Italy | "San Marino" | Switzerland | "Vatican City")
    echo -n "Italian"

    echo -n "unknown"


Save the custom script as a file and run it from the command line.


The script will ask you to enter a country. For example, if you type “Lithuania”, it will match the first pattern, and the echo command in that clause will be executed.

The script will print the following output:

Enter the name of a country: Lithuania
The official language of Lithuania is Lithuanian

If you enter a country that doesn’t match any other pattern except the default wildcard asterisk symbol, let’s say Argentina the script will execute the echo command inside the default clause.

Enter the name of a country: Argentina
The official language of Argentina is unknown



By now you should have a good understanding of how to write bash case statements. They are often used to pass parameters to a shell script from the command line. For example, the init scripts are using case statements for starting, stopping or restarting services.