Bash Case Statement

The case statement is a compound statement that evaluates an expression and executes the associated block of code based on the resulting value.
Bash Case Statement

On this page

In programming, control flow statements play a crucial role in determining the behavior of a program based on certain conditions. One such statement in Bash scripting is the case statement, which provides a concise and efficient way to handle multiple conditional cases.

For beginners, however, understanding how to use case statements can be a bit challenging. In this article, we'll delve into the fundamentals of bash case statements, offering detailed explanations and step-by-step code examples to simplify the concept.

Grasping the Basics

The case statement is a compound statement that evaluates an expression and executes the associated block of code based on the resulting value. It is particularly useful when you need to perform different actions based on various conditions or values of a variable.

The Syntax:

The fundamental structure of a bash case statement is as follows:

case expression in
    pattern1)
        # code block for pattern1
        ;;
    pattern2)
        # code block for pattern2
        ;;
    ...
     patternN)
        # code block for patternN
        ;;
    *)
        # default code block
        ;;
esac

Let's break down the different components of this syntax:

  • case expression in: This line initiates the case statement and specifies the expression to be evaluated.
  • pattern1), pattern2), ..., patternN): These are the different patterns or values that the expression can match. Each pattern is followed by a closing parenthesis ).
  • ;;: This is a case termination sequence, indicating the end of a particular case block.
  • *): This is the default case pattern, which will be executed if the expression doesn't match any of the specified patterns.
  • esac: This is the keyword used to terminate the case statement. It is simply the reversed form of the word "case".

Simple Case Statement

Let's start with a straightforward example where we use the case statement to handle different user inputs in a Bash script.

#!/bin/bash

echo "What's your favorite fruit? "
read fruit

case "$fruit" in
    "apple")
        echo "It's an apple!"
        ;;
    "banana")
        echo "It's a banana!"
        ;;
    *)
        echo "It's something else."
        ;;
esac

In this example, the script prompts the user to enter his favorite fruit. The case statement then evaluates the user's input ($fruit) and executes the corresponding block of code based on the provided fruit.

Here's a step-by-step breakdown of the code:

  • The script prompts the user to enter his favorite fruit using the echo command.
  • The read command is used to capture the user's input and store it in the variable fruit.
  • The case statement compares the value of $fruit against different patterns.
  • If it matches an "apple," it echoes "It's an apple!" and exits the case statement.
  • If it matches "banana," it echoes "It's a banana!" and exits the case statement.
  • If none of the patterns match, it echoes "It's something else."
💡
Notice the variable $fruit is enclosed in double quotes. This is to ensure proper handling of whitespace characters.

Pattern Ranges

You can use pattern ranges in bash case statements. Let's explore a scenario where we check if a number falls into a specific range:

#!/bin/bash

number=$1

case $number in
    [0-9])
        echo "The number is between 0 and 9."
        ;;
    1[0-9] | 2[0-9])
        echo "The number is between 10 and 29."
        ;;
    3[0-9] | 4[0-9])
        echo "The number is between 30 and 49."
        ;;
    *)
        echo "The number is outside the specified ranges."
        ;;
esac

Let me explain the script to you:

  • The script sets the variable number to the first argument of our script.
  • The case statement uses pattern ranges to check if the number falls within specific ranges.
  • If the number matches the first pattern, it echoes "The number is between 10 and 29."
  • If the number matches the second pattern, it echoes "The number is between 30 and 49."
  • If none of the patterns match, it echoes "The number is outside the specified ranges."

Instead of 1[0-9] | 2[0-9], we can also use [1-2][0-9]to match numbers from 10 to 29. Similarly, [3-4][0-9] is used to match numbers from 30 to 49:

#!/bin/bash

number=$1

case $number in

    [0-9])
        echo "The number is between 0 and 9."
        ;;
    [1-2][0-9])
        echo "The number is between 10 and 29."
        ;;
    [3-4][0-9])
        echo "The number is between 30 and 49."
        ;;
     5[0-9])
        echo "The number is between 50 and 59."
        ;;
    *)
        echo "The number is outside the specified ranges."
        ;;
esac

Advanced Usage

The case statement in Bash offers several advanced features that enhance its flexibility and power. Here are a few notable examples:

Pattern Matching

In addition to exact pattern matching, the case statement supports various pattern-matching techniques using wildcard characters and regular expressions. For example:


#!/bin/bash

filename=$1

case "$filename" in
    *.txt)
        echo "This is a text file."
        ;;
    *.png|*.jpg)
        echo "This is an image file."
        ;;
    [0-9]*)
        echo "This starts with a digit."
        ;;
esac

In this example, the patterns use wildcard characters (*, ?) and alternation (|) to match different types of files or strings based on their extensions or initial characters.

Command Substitution

The case statement can also be used in conjunction with command substitution, allowing you to evaluate the output of a command as the expression. This can be particularly useful when working with external programs or utilities.


#!/bin/bash

case "$(command)" in
    pattern1)
        # code block
        ;;
    pattern2)
        # code block
        ;;
    ...
esac

Combined Patterns

Multiple patterns can be combined in a single case block using the | operator, separating the patterns with pipe characters. This can help reduce code duplication and make the script more concise.


#!/bin/bash

case "$variable" in
    pattern1|pattern2|pattern3)
        # code block
        ;;
    ...
esac

We have seen this operator in action in our pattern ranges and pattern-matching examples.

Conclusion

By breaking down the syntax and providing clear examples, I hope this article has simplified bash case statements for you. Incorporate these concepts into your shell scripts to enhance your decision-making capabilities. As you become more familiar with case statements, you'll unlock new possibilities for efficient and structured script development.

Subscribe to sysxplore newsletter and stay updated.

Don't miss anything. Get all the latest posts delivered straight to your inbox. It's free!
Great! Check your inbox and click the link to confirm your subscription.
Error! Please enter a valid email address!