Introduction
The Bash case
statement is a form of the conditional if-elif-else statement. It simplifies complex conditions with multiple choices, making it more readable and easier to maintain than nested if
statements.
The case
statement tests input values and executes a corresponding command based on a matched pattern. It's ideal for various shell scripting tasks, such as creating menus, handling errors, or automating tasks like starting, stopping, or restarting services.
In this tutorial, you will learn the basics of the Bash case
statement and how to use it in Bash scripts.
Prerequisites
- A machine running Linux.
- Access to the command line interface (CLI).
- A text editor, such as Vi or Vim, for editing scripts.
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 works similarly to the switch case statement in other programming languages. It starts with the case
keyword followed by the $variable
and the in
keyword. Every pattern is followed by commands that execute if a match is found. The statement ends with the esac
keyword, which is case
spelled backward.
Variable
In a Bash case
statement, the variable holds a value that is used to compare against defined patterns. When the case
statement is executed, the script compares the input $variable
against each pattern in the defined order until it finds a match. Once a match is found, the corresponding command associated with the matched pattern is executed.
Patterns
In a Bash case
statement, a pattern and its associated commands create a clause that must end with ;;
. Patterns have specific operators and characteristics to improve their functionality:
- Patterns support special characters to enhance matching.
- The
)
operator terminates a pattern list. - The
|
operator separates multiple patterns and enables a single command to handle several inputs. - The script executes the commands corresponding to the first pattern that matches the input
$variable
. - The asterisk
*
symbol defines the default case, usually in the final pattern in the list.
Exit Status
The script in a Bash case
statement has two exit statuses:
- 0. The return status indicates the input did not match any defined pattern.
- Executed command status. If a command matches the input variable to a pattern, the exit status of the executed command is returned.
Note: If you are new to Bash, read our tutorial on Bash functions.
Bash case Statement Examples
The sections below show practical examples of using the Bash case
statement.
Example 1: Output a Description for Each Option
The following script lets the user choose a color and shows a comment based on the input using the echo command.
Follow the steps below:
1. Open the terminal and create the script file:
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 does the following:
- The first line (
#!/bin/bash
), known as the shebang, specifies the script interpreter (Bash). - Lines 2-7 represent the menu with options for the user.
- The Bash read command stores the user's choice in the
color
variable. - The
case
statement handles every possible input. Theecho
command provides an appropriate response based on the choice.
3. Save the script and exit Vi with:
:wq
4. Make the script executable using chmod:
chmod +x color.sh
5. Run the script:
./color.sh
The script offers a menu and outputs a different message depending on the selected option. Expand the script further with different colors to add more options.
Example 2: Using Multiple Patterns
The Bash case
statement allows multiple patterns in a clause. When the input variable matches any provided patterns, the script executes the commands in that clause.
This script below prompts the user to enter a month and outputs the number of days. Depending on the month, there are three possible answers:
- 28 or 29 days for February.
- 30 days for April, June, September, and November.
- 31 days for January, March, May, July, August, October, and December.
Follow the steps below to create the script:
1. Create the script month.sh by running:
vi month.sh
2. Add the following lines:
#!/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 -s nocasematch
builtin makes matching case-insensitive, preventing capitalization errors. - The pipe symbol
|
separates the patterns in a single clause.
3. Save the script and close Vi:
:wq
4. Make the script executable:
chmod +x month.sh
5. Run the script:
./month.sh
The script inputs are not case-sensitive and return the correct days for the chosen month.
Example 3: for Loops
Use a for loop in case
statements when there are many expressions to process. The following example returns all file types inside a directory:
1. Create the shell script:
vi filelist.sh
2. Enter the following lines to the file:
#!/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 lists all files in the current directory.
- The
for
loop iterates through each file. ${file##*.}
extracts the file extension by removing everything up to the last dot in the filename.- If found, the
case
statement compares the extension and outputs the file type.
3. Save the file and close Vi:
:wq
4. Make the script executable:
chmod +x filelist.sh
5. Execute the script:
./filelist.sh
The script finds and prints the file type of each file in the current directory. Expand the script by adding new extensions or prompting the user to input the directory.
Example 4: Create an Address Book
Use the case
statement to create a simple address book database and 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 to 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. Save the script and close the editor:
:wq
4. Make the script executable:
chmod +x phonebook.sh
5. 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. Add more contacts or new fields for each contact, such as a phone number or employment status.
Example 5: Check Character Type
The Linux shell enables dynamic matching, so the Bash case patterns can be flexible. 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 to the script file:
#!/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 or an empty line.";;
esac
In the above example:
- The control variable
$var
stores the input. - The square brackets
[]
denote a character range. Double square brackets[[]]
are for POSIX ranges. This approach is more efficient than usingif-else
statements to check each character individually. - The
?
character matches characters that aren't covered by previous conditions. It substitutes only one character. - The asterisk
*
matches all other possible inputs, including multiple characters or an empty line.
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. Save the file and close the text editor.
4. Change permissions to make the script executable:
chmod +x character.sh
5. Execute the script:
./character.sh
The script outputs the character type 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 how to use the Bash case
statement to simplify complex conditionals when working with multiple choices. Create different scripts to test patterns and process a command if a match is detected.
Next, see how to use Bash to read files line by line.