C.W.K.
Stream
Lesson 05 of 12 · published

Case Statements

~8 min · case, switch

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The shell's switch

case "$1" in
  start)   ./serve.sh & ;;
  stop)    pkill -f serve.sh ;;
  status)  pgrep -fa serve.sh ;;
  *)       echo "usage: $0 {start|stop|status}"; exit 2 ;;
esac

Each branch ends with ;;. Patterns are glob-style (*, ?, [abc]) and the first match wins. *) at the bottom is the default.

Multiple patterns per branch

case "$ext" in
  jpg|jpeg|png|gif|webp) echo image ;;
  mp4|mov|webm)          echo video ;;
  *.bak|*~|*.tmp)        echo trash ;;
  *)                     echo other ;;
esac

fallthrough (bash 4+, zsh)

End a branch with ;;& to continue testing the next patterns, or ;& to fall through to the next branch's body. Rare but useful.

When case beats if

If you find yourself writing more than two elifs with string equality, switch to case. It's flatter, easier to read, and faster on large alternatives. Most CLI dispatch in shell scripts (start|stop|status|reload) is a case statement.

Code

service-style dispatch·bash
#!/usr/bin/env bash
set -euo pipefail
case "${1:-}" in
  up)    docker compose up -d ;;
  down)  docker compose down ;;
  logs)  docker compose logs -f "${2:-}" ;;
  '')    echo 'usage: dev {up|down|logs}' >&2; exit 2 ;;
  *)     echo "unknown subcommand: $1" >&2; exit 2 ;;
esac

External links

Exercise

Write a categorize.sh path that uses case on the file extension to print image / video / archive / source / other. Test on a few of your own files.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.