Case Statements

Case statements allow you to test a string using a series of patterns, executing only the commands for the matching pattern. The general format of the case statement is:

case string in
    pattern_1)
        commands
        ;;
    pattern_2)
        commands
        ;;
   pattern_3)
        commands
       ;;
...
esac

The patterns you can use are:

  • * Matches any string of characters.

  • ? Matches any single character.

  • […] Matches any character or a range of characters in the brackets. A range is specified with a hyphen (e.g. A-Z or 1-4).

  • | Matches the pattern on either side of the | (e.g., John|Sam).

An example case statement is:

#!/bin/bash
name=John
case $name in
    john|John)
        echo Welcome $name
        ;;
    sam|Sam)
        echo Hello $name
        ;;
    *)
        echo You're not invited
       ;;
esac

The * is used for the ...

Get Spring Into Linux® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.