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.

Steps to use conditionals in Zsh:

  1. 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.

  2. 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.

  3. Run the script without the config file to confirm the first guard stops execution.
    $ zsh deploy-check.zsh
    missing config: config/settings.conf
  4. Create the config directory.
    $ mkdir -p config
  5. Write the required config file.
    $ printf 'region=us-east-1\n' > config/settings.conf
  6. Run the script without an environment value to confirm the string guard stops execution.
    $ zsh deploy-check.zsh
    missing environment
  7. 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
  8. Remove the sample files after testing.
    $ rm -rf config deploy-check.zsh