Bash Case Statements

In Bash, the case statement provides a way to perform multiple conditional checks on a variable or value. It allows you to match the value of a variable against a list of patterns and execute the corresponding code block for the first matching pattern. Here’s the basic syntax of a case statement in Bash:

case variable in
    pattern1)
        # code to execute if variable matches pattern1
        ;;
    pattern2)
        # code to execute if variable matches pattern2
        ;;
    pattern3)
        # code to execute if variable matches pattern3
        ;;
    *)
        # code to execute if variable matches none of the patterns
        ;;
esac

Each pattern can be a string or a pattern expression. When the case statement is executed, the value of the variable is compared against each pattern in the order they are listed. The code block following the matching pattern is executed, and the execution continues until the end of the case statement or until a ;; (double semicolon) is encountered, which indicates the end of a code block.

Here’s an example that demonstrates the usage of a case statement in Bash:

#!/bin/bash

fruit="apple"

case $fruit in
    "apple")
        echo "You selected an apple."
        ;;
    "banana")
        echo "You selected a banana."
        ;;
    "orange")
        echo "You selected an orange."
        ;;
    *)
        echo "You selected an unknown fruit."
        ;;
esac

In this example, the case statement checks the value of the fruit variable against different patterns. If the value matches a specific pattern, the corresponding code block is executed. If the value doesn’t match any of the patterns, the code block following *) (default case) is executed.

When you run this script, it will output:

You selected an apple.

You can add more patterns and corresponding code blocks to handle different cases based on the value of the variable. The case statement provides a convenient way to handle multiple conditional checks in a readable and structured manner within your Bash scripts.

Leave a Comment

Your email address will not be published. Required fields are marked *