Writing a Custom Error/die Function
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
#!/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
Login to try C/C++/Java/PHP code in the editor
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
#!/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 $?"
Login to try C/C++/Java/PHP code in the editor
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
#!/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"
Login to try C/C++/Java/PHP code in the editor
- Writing the error message to stdout instead of stderr, mixing diagnostics in with normal program output.
- Forgetting to actually call
exitinside the die function, which just prints a message but lets the script continue running in a broken state. - 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.
- A
diefunction 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
diefunction makes call sites read cleanly, e.g.[[ -f $file ]] || die "missing file: $file".
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments