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.

Frequently asked questions

How do you switch statement?
This task is covered in 3 stacks on this page: Bash & Linux, JavaScript, Python. The "Case Statement" snippet in Bash & Linux uses `case $variable in`.
Which command does the Bash & Linux example use?
The "Case Statement" snippet uses `case $variable in`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "switch statement" on this page?
Bash & Linux, JavaScript, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Case Statement": 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.