Handling Multiple Conditions in Bash Scripts
Discover diverse examples of case statements in Bash scripts, offering insights into handling multiple conditions efficiently.
From simple patterns to complex pattern matching and command output, these examples demonstrate the versatility of case statements in Bash. Whether you're a beginner or an experienced scripter, these examples provide valuable techniques for enhancing script functionality and managing various scenarios effectively.
Simple Case Statement with Single Pattern
fruit="apple"
case $fruit in
"apple")
echo "It's an apple."
;;
esac
Case Statement with Multiple Patterns
fruit="banana"
case $fruit in
"apple" | "banana")
echo "It's either an apple or a banana."
;;
esac
Case Statement with Pattern Ranges
num=5
case $num in
[1-5])
echo "The number is between 1 and 5."
;;
esac
Case Statement with Wildcard Pattern
filename="example.txt"
case $filename in
*.txt)
echo "It's a text file."
;;
esac
Case Statement with Pattern Matching using Regular Expressions
name="John"
case $name in
[A-Z][a-z]*)
echo "It's a capitalized name."
;;
esac
Case Statement with Fallthrough
fruit="orange"
case $fruit in
"apple")
echo "It's an apple."
;;
"orange" | "banana")
echo "It's an orange or a banana."
# Fallthrough
;;
"mango")
echo "It's a mango."
;;
esac
Case Statement with a Default Case
fruit="watermelon"
case $fruit in
"apple")
echo "It's an apple."
;;
"orange")
echo "It's an orange."
;;
*)
echo "It's an unknown fruit."
;;
esac
Case Statement with Variable Substitution
fruit="apple"
case ${fruit^^} in
"APPLE")
echo "It's an uppercase apple."
;;
esac
Case Statement with Complex Pattern Matching
fruit="grape"
case $fruit in
[a-z]*[aeiou])
echo "It's a fruit with a vowel ending."
;;
[A-Z]*)
echo "It's a capitalized fruit."
;;
*)
echo "It's an unknown fruit."
;;
esac
Case Statement with Command Output
fruit=$(echo "apple" | tr '[:lower:]' '[:upper:]')
case $fruit in
"APPLE")
echo "It's an uppercase apple."
;;
esac