Conditionals let Zsh scripts choose a path after checking files, variables, or numeric state. They are the branch points behind setup checks, deployment guards, and cleanup scripts that should stop when a required input is missing.
The if, elif, and else structure works with [[ ... ]] for file and string tests. Arithmetic checks use (( ... )), which reads numeric expressions without extra bracket syntax.
The example below checks for a configuration file, requires an environment name, and confirms that retries remain before printing a ready state. The syntax check covers the whole script, and the command output shows each guard before the final success path.
Related: How to set Zsh shell options
Related: How to debug a Zsh script
Related: How to use a case statement in Zsh
#!/usr/bin/env zsh
set -e
config_file="config/settings.conf"
environment=${ENVIRONMENT:-}
retries=3
if [[ ! -f $config_file ]]; then
print -r -- "missing config: $config_file"
exit 1
elif [[ -z $environment ]]; then
print -r -- "missing environment"
exit 1
elif (( retries > 0 )); then
print -r -- "environment=$environment"
print -r -- "config=$config_file"
print -r -- "status=ready"
else
print -r -- "no retries left"
exit 1
fi
Use [[ ... ]] for file and string tests. Use (( ... )) for numeric expressions such as retries > 0.
$ zsh -n deploy-check.zsh
No output from zsh -n means Zsh parsed the conditional chain without finding a syntax error.
$ zsh deploy-check.zsh missing config: config/settings.conf
$ mkdir -p config
$ printf 'region=us-east-1\n' > config/settings.conf
$ zsh deploy-check.zsh missing environment
$ ENVIRONMENT=production zsh deploy-check.zsh environment=production config=config/settings.conf status=ready
$ rm -rf config deploy-check.zsh