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
2
3
4
5
6
7
8
9
10
11
case $variable in
pattern1)
commands1
;;
pattern2)
commands2
;;
*)
default_commands
;;
esac

Key Features:

  1. Pattern Matching: You can use wildcards and regular expressions in your patterns.

  2. Multiple Patterns: Group several patterns together for the same code block.

  3. 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
    #!/bin/bash

    hour=$(date +%H)

    case $hour in
    0[0-9]|1[0-1])
    echo "Good morning!"
    ;;
    1[2-7])
    echo "Good afternoon!"
    ;;
    *)
    echo "Good evening!"
    ;;
    esac

    This script uses the case statement to match the current hour and output an appropriate greeting.

    Advanced Tips

  4. Use the | operator for multiple patterns:

    1
    2
    3
    4
    5
    case $fruit in
    apple|Apple)
    echo "It's an apple!"
    ;;
    esac
  5. Implement a menu system:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    echo "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" ;;
    esac
  6. Use case statements in functions:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    get_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!