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
Steps to use conditionals in Zsh:
- Create a script with file, string, and arithmetic conditionals.
- deploy-check.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.
- Check the script syntax before running it.
$ zsh -n deploy-check.zsh
No output from zsh -n means Zsh parsed the conditional chain without finding a syntax error.
- Run the script without the config file to confirm the first guard stops execution.
$ zsh deploy-check.zsh missing config: config/settings.conf
- Create the config directory.
$ mkdir -p config
- Write the required config file.
$ printf 'region=us-east-1\n' > config/settings.conf
- Run the script without an environment value to confirm the string guard stops execution.
$ zsh deploy-check.zsh missing environment
- Run the script with an environment value and confirm the ready state.
$ ENVIRONMENT=production zsh deploy-check.zsh environment=production config=config/settings.conf status=ready
- Remove the sample files after testing.
$ rm -rf config deploy-check.zsh
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.