← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 10 of 12

Writing a Custom Error/die Function

A die function is a small helper you write once that prints an error message and stops the script immediately, so you don't have to repeat that logic everywhere.

A Basic die Function

A die function prints its message to stderr and then exits, replacing repeated echo ... >&2; exit 1 blocks scattered through a script with one reusable call.

Example: A Basic die Function

bash
#!/bin/bash
die() {
    echo "ERROR: $1" >&2
    exit 1
}

check_positive() {
    if (( $1 <= 0 )); then
        die "value must be positive, got $1"
    fi
    echo "$1 is positive"
}

check_positive 5

Supporting a Custom Exit Code

Accepting an optional second argument for the exit code lets different failure conditions be distinguished by a caller inspecting the script's final exit status.

Example: Supporting a Custom Exit Code

bash
#!/bin/bash
die() {
    local message=$1
    local code=${2:-1}
    echo "ERROR: $message" >&2
    exit "$code"
}

(
    die "config file missing" 2
)
echo "the subshell that called die exited with status $?"

Using die at Validation Call Sites

Once defined, die reads naturally at the point of validation: condition || die "message" is a compact, readable guard clause.

Example: Using die at Validation Call Sites

bash
#!/bin/bash
die() {
    echo "ERROR: $1" >&2
    exit 1
}

required_tool="bash"
command -v "$required_tool" > /dev/null || die "$required_tool is required but not found"
echo "$required_tool is available, continuing"
Common Mistakes
  1. Writing the error message to stdout instead of stderr, mixing diagnostics in with normal program output.
  2. Forgetting to actually call exit inside the die function, which just prints a message but lets the script continue running in a broken state.
  3. Using a single generic exit code for every failure, making it impossible for callers to distinguish different kinds of errors from the script's exit status alone.
Chapter Summary
  • A die function centralizes error reporting: print to stderr, then exit with a non-zero status.
  • Accepting an optional exit code argument lets different call sites signal different failure types.
  • Printing to stderr (>&2) keeps error messages separate from a script's normal stdout output.
  • A die function makes call sites read cleanly, e.g. [[ -f $file ]] || die "missing file: $file".

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.