Skip to content

Bash case Statements

case is a clean alternative to lots of if/elif tests when matching patterns.

Example

#!/bin/bash
action="$1"
case "$action" in
  start) echo "Starting…";;
  stop) echo "Stopping…";;
  restart) echo "Restarting…";;
  *) echo "Usage: $0 {start|stop|restart}"; exit 1;;
esac

How to run it

  1. Save it to a file.
  2. Run chmod +x filename.sh where applicable.
  3. Run it from the terminal.

← Back homeRun in Sandbox →