Conditionals let a Bash script choose a path based on the state it sees at runtime. File checks, empty argument checks, numeric comparisons, and command exit statuses all become safer when the script tests them explicitly before continuing.

The common form is if ...; then ... elif ...; else ... fi. For file and string checks, the portable test command is written as [ condition ], while commands inside the condition are judged by their exit status.

The example checks whether the argument is missing, points to a non-empty file, points to an empty file, or names a path that does not exist. It uses real files so each branch can be verified from command output instead of only reading the script.

Steps to use conditionals in Bash scripts:

  1. Create the script with an argument check and file-state branches.
    check-input.sh
    #!/usr/bin/env bash
    set -euo pipefail
     
    input=${1:-}
     
    if [ -z "$input" ]; then
        printf "status=missing-path\n"
        exit 2
    fi
     
    if [ -f "$input" ] && [ -s "$input" ]; then
        printf "status=ready\n"
    elif [ -f "$input" ]; then
        printf "status=empty-file\n"
    else
        printf "status=not-found\n"
    fi

    -f checks for a regular file, -s checks that the file exists and has a size greater than zero, and -z checks for an empty string.

  2. Create an empty file for the empty-file branch.
    $ touch empty.txt
  3. Create a non-empty file for the ready branch.
    $ printf "ready\n" > ready.txt
  4. Check the script syntax.
    $ bash -n check-input.sh
  5. Verify the non-empty file branch.
    $ bash check-input.sh ready.txt
    status=ready
  6. Verify the empty-file branch.
    $ bash check-input.sh empty.txt
    status=empty-file
  7. Verify the not-found branch.
    $ bash check-input.sh missing.txt
    status=not-found

    Keep the missing-argument branch separate from the missing-file branch so callers can tell the difference between bad input and a path that does not exist.

  8. Verify the missing-argument branch.
    $ bash check-input.sh
    status=missing-path

    The script exits with status 2 after printing this output, so another script can treat missing input as a caller error.

  9. Remove the sample files when the branch tests are finished.
    $ rm -f check-input.sh empty.txt ready.txt