Bash Scripting - Case Statement

The case statement in Bash is a powerful way to perform multiple conditional checks in a concise and readable manner. It is particularly useful when you need to compare a variable against multiple values and execute different code blocks based on the matching condition.

Here's the basic syntax of a case statement:

case expression in pattern1) # code to be executed if expression matches pattern1 ;; pattern2) # code to be executed if expression matches pattern2 ;; pattern3) # code to be executed if expression matches pattern3 ;; *) # code to be executed if expression does not match any of the patterns ;; esac

Let's break down the components:

  1. case: It marks the beginning of the case statement.
  2. expression: This is the value that you want to compare against different patterns.
  3. in: It separates the expression from the list of patterns.
  4. pattern1, pattern2, pattern3: These are the possible values that the expression might match.
  5. ) and ;;: They mark the end of each pattern block. The double semicolon (;;) is used to terminate each block and move on to the next one.
  6. *: This is a wildcard pattern that matches anything. It is used as a default case if none of the previous patterns match.
Examples:

Basic String Matching

case $fruit in "apple") echo "It's a healthy choice!" ;; "banana") echo "Full of potassium!" ;; "orange") echo "Rich in vitamin C!" ;; *) echo "What a delicious fruit!" ;; esac

Numerical Ranges and Wildcards

case $number in {1..10}) echo "It's a small number." ;; {11..20}) echo "It's a medium number." ;; *) echo "It's a large number." ;; esac
case $letter in [aeiou]) echo "It's a vowel." ;; [bcdfghjklmnpqrstvwxyz]) echo "It's a consonant." ;; *) echo "Not a letter." ;; esac

Combining String and Numerical Comparisons

case $option in "-h" "--help") echo "Usage: my_script [-h] [-d directory]" exit 0 ;; "-d" "--directory") shift # Skip the "-d" option if [[ -d "$1" ]]; then directory="$1" else echo "Error: Directory '$1' does not exist." exit 1 fi ;; *) echo "Invalid option: '$option'" exit 1 ;; esac

Remember to enclose regular expressions in double quotes to prevent premature expansion.

Conclusion

The Bash case statement provides a flexible way to perform multiple conditional checks based on the value of a variable. It allows you to compare the variable against different patterns, executing specific code blocks for matching conditions and providing a default case for unmatched values using the wildcard (*) pattern.