Introduction
The bash case
statement is the simplest form of the if elif else conditional statement. The case
statement simplifies complex conditions with multiple different choices. This statement is easier to maintain and more readable than nested if
statements.
The case
statement tests the input value until it finds the corresponding pattern and executes the command linked to that input value. Thus, it is an excellent choice for creating menus where users select an option which triggers a corresponding action.
In this tutorial, you will learn the bash case
statement basics and how to use it in shell scripts.
Prerequisites
- A machine running Linux.
- Access to the command line.
- A text editor such as vi/vim.
Bash case Statement Syntax
The bash case
statement takes the following syntax:
case $variable in
pattern-1)
commands;;
pattern-2)
commands;;
pattern-3)
commands;;
pattern-N)
commands;;
*)
commands;;
esac
The case
statement starts with the case
keyword followed by the $variable
and the in
keyword. The statement ends with the case
keyword backwards - esac
.
$variable
- The script compares the input
$variable
against the patterns in each clause until it finds a match.
Patterns
- A pattern and its commands make a clause, which ends with
;;
. - Patterns support special characters.
- The
)
operator terminates a pattern list. - The
|
operator separates multiple patterns. - The script executes the commands corresponding to the first pattern matching the input
$variable
. - The asterisk
*
symbol defines the default case, usually in the final pattern.
Exit Status
The script has two exit statuses:
- 0. The return status when the input matches no pattern.
- Executed command status. If the command matches the input variable to a pattern, the executed command exit status is returned.
Note: If you are new to bash, read our tutorial on bash functions and how to use them.
Bash case Statement Examples
This section shows practical examples of using the bash case
statement.
Example 1: Output a Description for Each Option
The following example is a script that lets the user choose a color and shows a comment corresponding to the input using the echo command.
Follow the instructions below:
1. Open the terminal (Ctrl + Alt + T) and create the script:
vi color.sh
2. Add the following lines to the script:
#!/bin/bash
echo "Which color do you like best?"
echo "1 - Blue"
echo "2 - Red"
echo "3 - Yellow"
echo "4 - Green"
echo "5 - Orange"
read color;
case $color in
1) echo "Blue is a primary color.";;
2) echo "Red is a primary color.";;
3) echo "Yellow is a primary color.";;
4) echo "Green is a secondary color.";;
5) echo "Orange is a secondary color.";;
*) echo "This color is not available. Please choose a different one.";;
esac
Each of the lines has the following role:
- The first line in each script is typically the shebang (
#!
), which instructs the operating system which interpreter to use to parse the file. - Lines 2-7 are the options menu presented to the user to choose from.
- The
read color;
variable prompts the user for an answer and stores it. - The
case
statement contains the possible responses that correspond to the user's input. In this example, the output is theecho
command output. - The last line,
esac
, ends thecase
statement.
3. Save the script and exit vi with the following command:
:wq
4. Before running each script, make sure to chmod it to make it executable:
chmod +x color.sh
5. Run the script:
./color.sh
The script offers the options menu and outputs a different message depending on the selected option.
Example 2: Using Multiple Patterns
The case
statement allows using multiple patterns in each clause. If the expression matches the specified patterns, the script executes the commands in that clause.
This example script prompts the user to enter a month and outputs the number of days. There are three possible answers:
- 30 days.
- 31 days.
- 28 or 29 days for February.
Follow the steps below to create the script:
1. Create the script month.sh by running:
vi month.sh
2. Enter the following lines and save the script:
#!/bin/bash
shopt -s nocasematch
echo "Enter the name of a month."
read month
case $month in
February)
echo "There are 28/29 days in $month.";;
April | June | September | November)
echo "There are 30 days in $month.";;
January | March | May | July | August | October | December)
echo "There are 31 days in $month.";;
*)
echo "Unknown month. Please check if you entered the correct month name: $month";;
esac
In the example above:
- The
shopt
command with the-s nocasematch
option reduces the chance for error with the pattern matching being case insensitive. - The pipe symbol
|
separates the patterns in each of the clauses.
3. Make the script executable:
chmod +x month.sh
4. Run the script:
./month.sh
The script ignores differences in case and outputs the correct number of days in the selected month.
Example 3: for Loops
Use a for
loop in case
statements when there are many expressions to process. The following script returns all types of files from a directory.
Follow the steps below:
1. Create the shell script:
vi filelist.sh
2. Enter the following lines and then save the script:
#!/bin/bash
for file in $(ls)
do
Extension=${file##*.}
case "$Extension" in
sh) echo "Shell script: $file";;
md) echo "A markdown file: $file";;
png) echo "PNG image file: $file";;
txt) echo "A text file: $file";;
zip) echo "An archive: $file";;
conf) echo "A configuration file: $file";;
py) echo "A Python script: $file";;
*) echo "Unknown file type: $file";;
esac
done
In the example above:
- The ls command pulls a file list from the directory.
- The
for
loop applies file globbing to extract each file's extension.
3. Make the script executable:
chmod +x filelist.sh
4. Execute the script:
./filelist.sh
The script identifies each file type present in the current directory.
Note: The for loop is an essential programming functionality that goes through a list of elements. To learn how to use it efficiently in bash, check out our Bash for Loop detailed guide with examples.
Example 4: Create an Address Book
Use the case
statement to create a simple database and swiftly generate the requested information. The following example outputs the name, email address, and the selected person's address:
1. Create the script:
vi phonebook.sh
2. Add the following lines and save the script:
#!/bin/bash
echo "Choose a contact to display information:"
echo "[C]hris Ramsey"
echo "[J]ames Gardner"
echo "[S]arah Snyder"
echo "[R]ose Armstrong"
read person
case "$person" in
"C" | "c" ) echo "Chris Ramsey"
echo "[email protected]"
echo "27 Railroad Dr. Bayside, NY";;
"J" | "j" ) echo "James Gardner"
echo "[email protected]"
echo "31 Green Street, Green Cove Springs, FL";;
"S" | "s") echo "Sarah Snyder"
echo "[email protected]"
echo "8059 N. Hartford Court, Syosset, NY";;
"R" | "r") echo "Rose Armstrong"
echo "[email protected]"
echo "49 Woodside St., Oak Forest, IL";;
*) echo "Contact doesn't exist.";;
esac
3. Chmod the script:
chmod +x phonebook.sh
3. Execute the script:
./phonebook.sh
The script outputs the contact details for the selected person. Selecting an option that isn't listed notifies the user that the contact doesn't exist.
Example 5: Check Character Type
The following example shows how to use the case
statement to check which character type the user has entered.
Follow the steps below:
1. Create the script:
vi character.sh
2. Add the following lines and save the script:
#!/bin/bash
echo "Enter a character:"
read var
case $var in
[[:lower:]) echo "You entered a lowercase character.";;
[[:upper:]]) echo "You entered an uppercase character.";;
[0-9]) echo "You entered a digit.";;
?) echo "You entered a special character.";;
*) echo "You entered multiple characters.";;
esac
In the above example:
- The
$var
control variable stores the input. - Instead of typing all possible combinations to match against, use the square brackets
[]
to denote a character range. Use double square brackets[[]]
for POSIX ranges.if-else
requires entering each character condition individually. - The
?
character covers characters that aren't lowercase, uppercase, or digits. It substitutes only one character, as opposed to*
which replaces everything else not covered by the conditions above.
Note: Although it is possible to use [a-z]
to denote a lowercase character range, uppercase characters are trapped as well on some Linux distributions.
3. Change permissions to make the script executable:
chmod +x character.sh
4. Execute the script:
./character.sh
The output states the type of character entered after matching it against the specified conditions.
Note: Learn how to compare strings using a Bash script with our guide Bash String Comparison.
Conclusion
This guide showed you how to use the bash case
statement to simplify complex conditionals when working with multiple choices. Create different scripts to test strings against patterns and process a command line if a match is detected. Implement different commands or loops to create advanced bash scripts.