Switch statement

3 snippets across 3 stacks — Bash & Linux, JavaScript, Python

SHBash & Linux

Case Statement

SH · Bash Scripting
syntax
case $variable in
  pattern1) commands ;;
  pattern2) commands ;;
  *) default ;;
esac
example
case "$1" in
  start)
    echo "Starting service..."
    systemctl start myapp
    ;;
  stop|restart)
    echo "${1}ing service..."
    systemctl "$1" myapp
    ;;
  status)
    systemctl status myapp
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
    ;;
esac

Note Each branch ends with ;;. Patterns support globbing and | for alternatives. case is cleaner than long if/elif chains when matching a single variable against many values. *) is the default/catch-all branch.

JSJavaScript

switch Statement

JS · Control Flow
syntax
switch (expression) {
  case value: ... break;
  default: ...
}
example
function getStatusText(code) {
  switch (code) {
    case 200: return "OK";
    case 301: return "Moved Permanently";
    case 404: return "Not Found";
    case 500: return "Internal Server Error";
    default:  return `Unknown (${code})`;
  }
}
console.log(getStatusText(404));
output
"Not Found"

Note Uses strict equality (===). Forgetting break causes fall-through to the next case. Using return instead of break is a clean pattern in functions.

PYPython

match / case (Structural Pattern Matching)

PY · Control Flow
syntax
match subject:
    case pattern:
        ...
example
command = {"action": "move", "x": 10, "y": 20}

match command:
    case {"action": "move", "x": x, "y": y}:
        print(f"Moving to ({x}, {y})")
    case {"action": "stop"}:
        print("Stopping")
    case _:
        print("Unknown command")
output
Moving to (10, 20)

Note match/case (Python 3.10+) is structural pattern matching, not just a switch. It can destructure dicts, sequences, and objects in the pattern.