How to use case statements in Bash

A case statement is a conditional statement in Bash that allows you to compare a variable with multiple values. This type of comparison is accomplished with if statements, but case statements are a better alternative to writing them simply and concisely.

The way case statements are used in Bash is similar to how switch statements are used in languages like Java and JavaScript.

Syntax

Let's look into the widget below to understand the case statement syntax in Bash better:

case variable in
pattern1)
action1
;;
pattern2)
action2
;;
...
*)
default_command
;;
esac
Syntax for case statements in Bash

Here’s what each keyword in the syntax above means:

  • case signifies the beginning of the case statement.

  • variable in compares the value in the variable according to each pattern; if it evaluates to true, then the action belonging to that pattern is executed.

  • pattern1 and pattern2 represent the values to which the variable is compared.

  • action1 and action2 commands are executed once a pattern matching evaluates to true.

  • ;; represent the block end; it represents the end of the code block and stops from continuous execution once an action is executed.

  • *) is a default case that is executed when patterns don't match.

  • esac signifies the end of the case statement.

Example

After getting a proper understanding of the syntax, its time for us to get hands-on experience with the following widget:

#!/bin/bash
read action
case $action in
"code")
echo "Write some code"
;;
"sleep")
echo "Take some rest"
;;
"exercise")
echo "Time for gym"
;;
*)
echo "Do nothing"
;;
esac

Enter the input below

The example above illustrates how to use case statements in Bash.

Free Resources