How to Use the case
Statement in Bash
The case
statement in Bash is a powerful control structure that allows you to execute different commands based on the value of a variable or expression. It is particularly useful when you have multiple conditions to evaluate, making your code cleaner and more readable compared to using multiple if
statements.
Basic Syntax of the case
Statement
The basic syntax of a case
statement is as follows:
case variable in
pattern1)
# commands for pattern1
;;
pattern2)
# commands for pattern2
;;
*)
# commands if no patterns match
;;
esac
In this syntax:
variable
is the value being evaluated.pattern1
,pattern2
, etc., are the patterns to match against the variable.- The
;;
marks the end of each case block. *
is a wildcard that matches anything, serving as a default case if no patterns match.esac
marks the end of thecase
statement.
Example of a case
Statement
Here’s a simple example of using a case
statement to evaluate a variable representing a day of the week:
#!/bin/bash
# Prompt the user for a day of the week
echo "Enter a day of the week:"
read day
case $day in
Monday)
echo "Start of the work week."
;;
Tuesday)
echo "Second day of the work week."
;;
Wednesday)
echo "Midweek day."
;;
Thursday)
echo "Almost the weekend!"
;;
Friday)
echo "Last day of the work week."
;;
Saturday|Sunday)
echo "It's the weekend!"
;;
*)
echo "Invalid day entered."
;;
esac
In this example:
- The user is prompted to enter a day of the week, which is stored in the variable
day
. - The
case
statement evaluates the value ofday
against various patterns. - Depending on the input, the script prints a corresponding message.
- The
Saturday|Sunday
pattern uses the pipe symbol (|
) to match either Saturday or Sunday. - If the input does not match any of the specified patterns, the default case (
*
) is executed, printing "Invalid day entered."
Using Wildcards in Patterns
You can also use wildcards in patterns to match multiple values. For example:
#!/bin/bash
# Prompt the user for a fruit
echo "Enter a fruit:"
read fruit
case $fruit in
apple|banana|cherry)
echo "$fruit is a fruit."
;;
carrot|broccoli)
echo "$fruit is a vegetable."
;;
*)
echo "$fruit is neither a fruit nor a vegetable."
;;
esac
In this example:
- The script checks if the input fruit is either an apple, banana, or cherry, and prints that it is a fruit.
- If the input is a carrot or broccoli, it prints that it is a vegetable.
- If the input does not match any of the specified patterns, the default case executes, indicating that the input is neither a fruit nor a vegetable.
Conclusion
The case
statement is a versatile and efficient way to handle multiple conditions in Bash scripting. It enhances code readability and maintainability, especially when dealing with numerous potential values for a variable. By using the case
statement, you can streamline your scripts and make them easier to understand.