TExcelTAD
Home › Linux & Bash › Bash case

Bash case

case compares one value against a list of patterns and runs the block of the first one that matches. It's cleaner than a long if/elif chain when you check a single variable against many possibilities, such as menu choices, command names or file extensions.

Syntax

bash · try it yourself
day="sat"
case $day in
  mon|tue|wed|thu|fri)
    echo "weekday"
    ;;
  sat|sun)
    echo "weekend"
    ;;
  *)
    echo "unknown day: $day"
    ;;
esac
weekend
  • Each branch is pattern) followed by commands and ends with ;;.
  • | separates alternative patterns.
  • *) matches anything: the default branch, by convention last.
  • The statement ends with esac (case backwards).

Patterns are globs

Patterns use the same wildcards as file names: * any text, ? one character, [...] a character set. This makes case great for classifying strings:

bash · try it yourself
for file in photo.JPG notes.txt archive.tar.gz script.sh Makefile; do
  case $file in
    *.jpg|*.JPG|*.png) type="image" ;;
    *.tar.gz|*.zip)    type="archive" ;;
    *.sh)              type="shell script" ;;
    *.*)               type="other file" ;;
    *)                 type="no extension" ;;
  esac
  printf '%-15s %s\n' "$file" "$type"
done
photo.JPG       image
notes.txt       other file
archive.tar.gz  archive
script.sh       shell script
Makefile        no extension

The first matching branch wins, so put specific patterns before general ones: *.* would also match archive.tar.gz if it came first.

Character classes and answers

bash · try it yourself
classify() {
  case $1 in
    [0-9]*)       echo "$1: starts with a digit" ;;
    [A-Z]*)       echo "$1: starts with a capital" ;;
    [a-z]*)       echo "$1: starts with a lower-case letter" ;;
    "")           echo "(empty input)" ;;
    *)            echo "$1: starts with a symbol" ;;
  esac
}
classify 42abc
classify Linux
classify bash
classify "#tag"
classify ""
42abc: starts with a digit
Linux: starts with a capital
bash: starts with a lower-case letter
#tag: starts with a symbol
(empty input)

A classic use is accepting yes/no answers in any spelling:

bash · try it yourself
for answer in y Yes NO maybe; do
  case ${answer,,} in
    y|yes) echo "$answer -> confirmed" ;;
    n|no)  echo "$answer -> cancelled" ;;
    *)     echo "$answer -> please answer yes or no" ;;
  esac
done
y -> confirmed
Yes -> confirmed
NO -> cancelled
maybe -> please answer yes or no

${answer,,} lower-cases the value first, so the patterns only need lower-case spellings.

Subcommands: the script dispatcher

Many tools have the form tool start, tool stop, tool status. A case on the first argument is the standard way to build that:

bash · try it yourself
cat > service.sh <<'SCRIPT'
#!/usr/bin/env bash
case $1 in
  start)   echo "Starting app..." ;;
  stop)    echo "Stopping app..." ;;
  restart) "$0" stop; "$0" start ;;
  status)  echo "app is running" ;;
  *)       echo "Usage: $0 {start|stop|restart|status}" >&2; exit 2 ;;
esac
SCRIPT
chmod +x service.sh
./service.sh start
./service.sh restart
./service.sh reload
echo "exit status: $?"
Starting app...
Stopping app...
Starting app...
Usage: ./service.sh {start|stop|restart|status}
exit status: 2

The default branch prints a usage message to standard error (>&2) and exits with a non-zero status, which is what well-behaved command-line tools do.

Fall-through: ;& and ;;&

Bash has two less common terminators:

Terminator Effect
;; Stop after this branch (normal)
;& Also run the next branch's commands without testing it
;;& Continue testing the remaining patterns
bash · try it yourself
level="warn"
case $level in
  debug) echo "showing debug" ;&
  info)  echo "showing info" ;&
  warn)  echo "showing warnings" ;&
  error) echo "showing errors" ;;
esac
showing warnings
showing errors

Starting at warn, execution falls through to error: a neat way to say "this level and everything more severe".

Test yourself

Which keyword ends a case statement?

  1. end
  2. done
  3. esac
  4. fi

What does the pattern *) do?

  1. Matches only *
  2. Matches anything: the default branch
  3. Matches files
  4. Ends the case

With case $f in *.*) ... ;; *.zip) ... ;; esac, which branch runs for a.zip?

  1. *.zip
  2. *.*
  3. Both
  4. Neither