Bash Case Statement
Bash Case Statement
In Bash scripting, the case statement allows you to make decisions based on the value of a variable. It provides a way to simplify complex conditional operations by matching a variable against multiple patterns.
Syntax
case "$variable" in
pattern1)
# commands for pattern1
;;
pattern2)
# commands for pattern2
;;
*)
# default commands
;;
esac
The basic syntax involves using case
followed by the variable in double quotes, patterns to match against, and the commands to execute for each pattern. The ;;
marks the end of each pattern's commands, and esac
ends the case statement.
Example Bash Case Statements
Let's look at some examples of how to use case statements in Bash:
1. Case Statement for Day of the Week
This script checks the value of the variable day
and prints a message based on the day of the week.
#!/bin/bash
day="Monday"
case "$day" in
"Monday")
echo "Today is Monday."
;;
"Tuesday")
echo "Today is Tuesday."
;;
"Wednesday")
echo "Today is Wednesday."
;;
*)
echo "It's another day."
;;
esac
In this script, the variable day
is assigned the value 'Monday'. The case statement checks the value of day
and matches it against the patterns 'Monday', 'Tuesday', and 'Wednesday'. If none of these patterns match, the default case prints a message indicating it's another day.
2. Case Statement for User Input
This script prompts the user to enter a number between 1 and 3 and prints a corresponding message.
#!/bin/bash
read -p "Enter a number between 1 and 3: " number
case "$number" in
1)
echo "You entered one."
;;
2)
echo "You entered two."
;;
3)
echo "You entered three."
;;
*)
echo "Invalid input."
;;
esac
In this script, the user is prompted to enter a number between 1 and 3. The case statement checks the value of number
and matches it against the patterns 1, 2, and 3. If none of these patterns match, the default case prints a message indicating invalid input.
3. Case Statement for File Type
This script checks the extension of a filename and prints a message based on the file type.
#!/bin/bash
filename="document.txt"
case "$filename" in
*.txt)
echo "It's a text file."
;;
*.jpg)
echo "It's an image file."
;;
*.sh)
echo "It's a shell script."
;;
*)
echo "Unknown file type."
;;
esac
In this script, the variable filename
is assigned the value 'document.txt'. The case statement checks the extension of filename
and matches it against the patterns '*.txt', '*.jpg', and '*.sh'. If none of these patterns match, the default case prints a message indicating an unknown file type.
Conclusion
The Bash case statement
is a powerful tool for simplifying complex conditional operations in shell scripting. Understanding how to use case statements can help you create more efficient and readable scripts.