Case Statement in Bash
Are you looking to streamline your Bash scripts and make them more efficient? Look no further than the powerful switch (case) statement! In this blog post, we’ll dive deep into how to use this versatile control structure in Bash scripting.
What is a Switch (Case) Statement?
The switch statement, known as the “case” statement in Bash, allows you to compare a given value against multiple patterns and execute different code blocks based on which pattern matches. It’s an excellent alternative to long chains of if-else statements when you need to handle multiple conditions.
Basic Syntax
1 | case $variable in |
Key Features:
- Pattern Matching: You can use wildcards and regular expressions in your patterns.
- Multiple Patterns: Group several patterns together for the same code block.
Fall-through: Use the ;& operator to continue checking subsequent patterns.
Example
Let’s create a simple script that greets users based on the time of day:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
hour=$(date +%H)
case $hour in
0[0-9]|1[0-1])
echo "Good morning!"
;;
1[2-7])
echo "Good afternoon!"
;;
*)
echo "Good evening!"
;;
esacThis script uses the case statement to match the current hour and output an appropriate greeting.
Advanced Tips
Use the
|
operator for multiple patterns:1
2
3
4
5case $fruit in
apple|Apple)
echo "It's an apple!"
;;
esacImplement a menu system:
1
2
3
4
5
6
7
8
9
10
11
12
13echo "Select an option:"
echo "1) Option 1"
echo "2) Option 2"
echo "3) Quit"
read choice
case $choice in
1) echo "You selected Option 1" ;;
2) echo "You selected Option 2" ;;
3) echo "Goodbye!"; exit ;;
*) echo "Invalid option" ;;
esacUse case statements in functions:
1
2
3
4
5
6
7
8
9get_day_type() {
case $1 in
Saturday|Sunday) echo "weekend" ;;
*) echo "weekday" ;;
esac
}
day_type=$(get_day_type "Monday")
echo "Monday is a $day_type"Conclusion
The switch (case) statement in Bash is a powerful tool for creating more readable and efficient scripts. By mastering this control structure, you’ll be able to handle complex conditionals with ease and write cleaner, more maintainable code.
Remember to experiment with different patterns and use cases to fully leverage the power of the case statement in your Bash scripts!