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.
Related: How to use conditionals in Zsh
Related: How to use getopts in Zsh
Related: Use a case statement in Bash
Steps to use a case statement in Zsh:
- 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.
- 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.
- Add the production branch after the staging branch.
(prod|production) url=https://www.example.com ;; - Close the case block with missing-target and catch-all guards.
("") print -u2 -- "missing target" exit 2 ;; (*) print -u2 -- "unknown target: $target" exit 2 ;; esacA leading * branch matches every target and prevents later specific branches from running.
- Append the selected target and URL output after esac.
print -r -- "target=$target" print -r -- "url=$url"
- 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.
- Run the shared prod|production branch with its short alias.
$ zsh deploy-target.zsh prod target=prod url=https://www.example.com
- Run an unsupported target to exercise the catch-all branch.
$ zsh deploy-target.zsh sandbox unknown target: sandbox
- 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.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.