Advanced Bash Scripting

Streams

Exit code

Applications and commands in Unix return an exit status—a numerical code indicating success or failure. By convention, a zero exit code means success, while any non-zero code signals an error. Understanding these codes is crucial for writing robust shell scripts and ensuring predictable automation.

Analogy: The Food Delivery Driver

Consider a food delivery driver verifying an address before dispatch. If the address is correct, the driver proceeds. If it’s wrong, they return with an error report. This mirrors how scripts and commands operate: they check conditions, perform tasks, and then report their status.

The image shows a graphic of a smartphone with a map and location pins, alongside an icon of a delivery person on a scooter. There are checkmarks next to "Address" and "Task completion."

How Exit Codes Work in Unix

Every Unix-based command finishes with an exit code:

  • 0: Success
  • Non-zero: An error occurred

The image displays the text "Exit Code" with the number "0" and a checkmark, indicating a successful operation.

Common Exit Codes Table

Exit CodeDescription
0Success
1General error
2Misuse of shell builtins
126Command invoked cannot execute
127Command not found
128+Fatal error (invalid argument to exit)

Warning

Exit codes are constrained to the range 0–255. Any value above 255 wraps around modulo 256.

Certain exit codes are reserved by the shell or operating system. Defining your own codes (above 2) helps callers distinguish between different failure modes.

Custom Exit Codes in Your Script

Below is a template that checks for a configuration file and terminates with meaningful exit statuses.

#!/usr/bin/env bash

export CONF_FILE="/var/tmp/file.conf"

terminate() {
    local message="$1"
    local code="${2:-1}"
    echo "${message}" >&2
    exit "${code}"
}

echo "Starting script execution"
echo "Sourcing configuration file"
if [[ ! -f "${CONF_FILE}" ]]; then
    terminate "Configuration file not found: ${CONF_FILE}" 2
fi

exit 0

Note

Use clear, documented exit codes in your scripts. This makes it easier for users and other scripts to handle errors automatically.

References

Watch Video

Watch video content

Practice Lab

Practice lab

Previous
Pipefail
Next
Xargs