Bash Shell ScriptingThe if statement can be game-changing in a shell script’s logic process, but it is not the only option, and therefore not the ideal solution in every instance.

It is possible, for example, to use the if-elif-else-fi process to evaluate the value of a variable, and perform different actions based on its value, but there is a more clean-cut solution.

The case statement — or switch statement — is that solution.

A case statement will evaluate a single expression (variable, etc.) against a number of specified values/patterns/etc., each of which will perform different actions if they are a match.

Let’s look at the syntax, and then jump right into an example after that.

Syntax

The case statement syntax is, at first glance, more confusing than the if statement, but only until it’s broken down into small pieces for easier digestion.

The basic syntax is:

case EXPRESSION in
    PATTERN1)
        action(s) to perform
        ;;
    PATTERN2)
        action(s) to perform
        ;;
    *)
        action(s) to perform
        ;;
esac

The case statement begins with the word “case”, followed by the expression that will be evaluated, and the word “in”.

After that, as many patterns as necessary can be specified, to be evaluated against the expression. Each pattern is immediately followed by an end parenthesis, followed by a new line. Each block of actions to be performed (if that pattern matches the expression) ends with two semicolons on a new line.

The case statement “else” equivalent — for actions to be performed if none of the patterns were a match — is an asterisk, followed by the end parenthesis and the same actions/end-block-semicolons sequence as any other pattern block.

The case statement ends with “esac”, which is “case”, spelled backward.

Case Statement Example

There are so many useful shell scripts that could be written, yet here I am writing another useless (and rather fun?) script.

At the very least, it is a working example of a case statement in action, which can be modified to suit your (hopefully useful!) needs.

#!/bin/bash
read -p "What is your favorite dog breed?: " breed

case $breed in
     mastiff|"saint bernard")
          echo "Ok, that's a pretty big dog!"
          ;;
     dalmation)
          echo "Sounds kind of spotty!"
          ;;
     "shiba inu")
          echo "Hey, they're my favorite, too!"
          ;;
     *)
          echo "I have no comment about ${breed}s."
          ;;
esac

exit 0

Conclusion

Plot out your script in advance to determine if an if statement, a case statement, or something else entirely should be used for the task(s) that you are setting out to accomplish.

It may be that a loop is what is required for a task at hand, which sets the stage for our upcoming lesson on shell script control structure loops.