Case statements in Bash provide a powerful and readable way to handle multiple conditions in shell scripts. They offer an alternative to complex if-else statements when dealing with multiple possible values of a variable.
The basic syntax of a Bash case statement is as follows:
case expression in
pattern1)
commands1
;;
pattern2)
commands2
;;
*)
default_commands
;;
esac
Each pattern is followed by a closing parenthesis, commands to execute, and two semicolons (;;) to indicate the end of that case.
Case statements are particularly useful for menu-driven scripts or command-line argument parsing. Here's a simple example:
#!/bin/bash
echo "Enter a fruit name:"
read fruit
case $fruit in
"apple")
echo "It's a red fruit."
;;
"banana")
echo "It's a yellow fruit."
;;
"orange")
echo "It's an orange fruit."
;;
*)
echo "Unknown fruit."
;;
esac
In this example, the script prompts for a fruit name and responds based on the input. The asterisk (*) acts as a catch-all for any unmatched patterns.
Bash case statements support pattern matching using wildcards:
*
: Matches any string?
: Matches any single character[...]
: Matches any one of the enclosed charactersHere's an example demonstrating pattern matching:
case $1 in
start|START)
echo "Starting the service"
;;
stop|STOP)
echo "Stopping the service"
;;
restart|RESTART)
echo "Restarting the service"
;;
[0-9]*)
echo "Numeric input detected"
;;
*)
echo "Usage: $0 {start|stop|restart}"
;;
esac
This script uses command-line arguments and demonstrates case-insensitive matching and numeric pattern matching.
Bash case statements offer a clean and efficient way to handle multiple conditions in shell scripts. They improve readability and maintainability compared to nested if-else structures, especially when dealing with multiple possible values of a variable or command-line argument.
By mastering case statements, you'll enhance your ability to write more elegant and efficient Bash scripts. Remember to combine them with other Bash features like functions and loops for even more powerful scripting capabilities.