A shell script often needs to turn one short input into a defined action without scattering string tests across the file. A Zsh case statement keeps those choices together and stops at the first pattern that matches.

Each branch begins with a pattern followed by ) and ends with ;;. Zsh accepts a parenthesized pattern such as (prod|production), while the | separator lets either word select the same branch.

The target router keeps the selected URL in one variable and reserves exit status 2 for invalid input. A syntax check catches an unfinished branch before execution, a recognized alias prints its assigned URL, and the catch-all branch provides fail-capable proof for an unsupported target.

Steps to use a case statement in Zsh:

  1. Create deploy-target.zsh with its interpreter, strict options, and first-argument input.
    deploy-target.zsh
    #!/usr/bin/env zsh
    setopt ERR_EXIT NO_UNSET
     
    target=${1:-}

    The :- form leaves target empty when no first argument was supplied, and NO_UNSET still catches other accidental reads of undefined parameters.

  2. Add the development and staging branches after the target assignment.
    case $target in
        (dev|development)
            url=https://dev.example.com
            ;;
        (stage|staging)
            url=https://staging.example.com
            ;;

    The opening parenthesis is valid Zsh case syntax. Each | pattern sends two accepted names to one assignment.

  3. Add the production branch after the staging branch.
        (prod|production)
            url=https://www.example.com
            ;;
  4. Close the case block with missing-target and catch-all guards.
        ("")
            print -u2 -- "missing target"
            exit 2
            ;;
        (*)
            print -u2 -- "unknown target: $target"
            exit 2
            ;;
    esac

    A leading * branch matches every target and prevents later specific branches from running.

  5. Append the selected target and URL output after esac.
    print -r -- "target=$target"
    print -r -- "url=$url"
  6. Check deploy-target.zsh for Zsh syntax errors.
    $ zsh -n deploy-target.zsh

    No output means Zsh parsed the completed case statement without finding a syntax error.

  7. Run the shared prod|production branch with its short alias.
    $ zsh deploy-target.zsh prod
    target=prod
    url=https://www.example.com
  8. Run an unsupported target to exercise the catch-all branch.
    $ zsh deploy-target.zsh sandbox
    unknown target: sandbox
  9. Print the catch-all command's exit status without running another command first.
    $ printf 'exit=%s\n' "$?"
    exit=2

    A status of 2 distinguishes rejected input from a recognized branch, which returns 0. The shell replaces $? after any later command.