Sub topic 7
Exit Status: Making Failures Loud
This chapter assumes you can write basic shell scripts, know that every command returns an exit code, and have read the earlier chapters on cron, systemd timers and capturing logs. Here the focus is on making a job's failure visible to a person or a monitoring system.
Why exit status matters
Every process ends with an exit status, a number from 0 to 255. By convention, 0 means success and anything else means failure. Schedulers, shells and monitoring tools all depend on this one number. If your script exits 0 after a failure, nothing downstream can tell that something went wrong.
Shell scripts are especially prone to this. By default, bash keeps going after a failed command. The exit status of the whole script is the status of the last command it ran. A script whose last line is echo done therefore reports success even if the database dump on line 3 failed.
#!/usr/bin/env bash
# Broken on purpose: reports success even when pg_dump fails
pg_dump mydb > /var/backups/db.sql
echo "backup finished"Running this with a missing database prints an error, then backup finished, then exits 0. Cron sees a clean run and sends nothing.
Strict mode: set -euo pipefail
Three bash options turn silent failures into stops.
| Option | Effect | What it catches | Column |
|---|---|---|---|
| `set -e` | Exit when a simple command fails | A failed `pg_dump` on its own line | |
| `set -u` | Treat unset variables as errors | A typo such as `$BACKUP_DRI`, or an unset variable in `rm -rf "$DIR/"` | |
| `set -o pipefail` | A pipeline fails if any stage fails | `pg_dump mydb \ | gzip` when `pg_dump` fails but `gzip` succeeds |
The pipeline option is the one people forget. Without it, pg_dump mydb | gzip > file returns the status of gzip alone. You get a valid, empty-looking archive and a success code.
#!/usr/bin/env bash
set -euo pipefail
pg_dump mydb | gzip > /var/backups/db.sql.gz
echo "backup finished"Now a failed pg_dump stops the script before echo runs, and the script exits with a non-zero status.
Limits of set -e
set -e has exceptions that surprise people. It does not trigger when the failing command is:
- part of an
if,whileoruntilcondition, - on the left side of
&&or||, - any command in a
&&or||list except the last, - inside a command whose status is negated with
!.
It also behaves differently inside functions that are called from a tested context. In that case, set -e is ignored for the whole function body.
#!/usr/bin/env bash
set -euo pipefail
cleanup() {
rm /tmp/does-not-exist # fails
echo "cleanup continues" # still runs when cleanup is called in an if
}
if cleanup; then
echo "cleanup reported success"
fiThis prints both messages. The rm failed, but because cleanup was used as an if condition, set -e was suspended inside it. For critical steps, check the status yourself.
if ! pg_dump mydb | gzip > "$tmp"; then
echo "dump failed" >&2
exit 1
fiThink of set -euo pipefail as a safety net, not a full error-handling strategy. Combine it with explicit checks at the steps that matter most.
Choosing exit codes deliberately
Any non-zero code means failure to cron and systemd, but distinct codes help humans and wrappers. Keep to a small, documented set.
| Code | Common meaning |
|---|---|
| 0 | Success |
| 1 | General failure |
| 2 | Misuse of the command (bad arguments) |
| 124 | `timeout` ran out of time |
| 126 | Command found but not executable |
| 127 | Command not found |
| 128+N | Killed by signal N (137 is SIGKILL, 143 is SIGTERM) |
Codes 126 and 127 are common in cron jobs. They usually mean the PATH or the file permissions are wrong, as covered in the chapter on cron's environment.
Avoid exiting with a value above 255, because the shell reduces it modulo 256. Exit 256 becomes 0, which reports success.
Using trap to report failures
A trap runs a command when the script exits or receives a signal. The ERR trap fires when a command fails, and EXIT fires on any exit. Use EXIT for cleanup and ERR for context.
#!/usr/bin/env bash
set -Eeuo pipefail
on_error() {
local code=$? line=$1
echo "$(date -Is) FAILED exit=$code line=$line" >&2
}
trap 'on_error $LINENO' ERR
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
pg_dump mydb | gzip > "$tmp"
echo "ok"The capital -E makes the ERR trap apply inside functions and subshells as well. The error message goes to standard error, which cron mails and systemd sends to the journal. The EXIT trap does not change the exit status, so the script still reports the original failure.
How each scheduler reacts to a failure
The two schedulers treat a non-zero exit differently. Knowing what each does determines where you must add your own alerting.
Mermaid is not available in a nested fence, so the flow is shown in the diagram below.
Cron
Cron does not record the exit status of a job anywhere. It only reacts to output. If the job writes to standard output or standard error and MAILTO is set with a working mail system, cron mails that output. A job that fails with no output produces no mail, and nobody learns of the failure. A job that succeeds but prints a line also produces mail, which trains people to ignore it.
Two practical rules follow:
- Make failures write a message to standard error.
- Make successes quiet, or redirect their output to a log file.
If you redirect everything with >> /var/log/sync.log 2>&1, cron has nothing to mail, so a failure becomes invisible unless you monitor the log or the heartbeat. Choose one visible channel for failure on purpose.
systemd
systemd tracks the result of every service. A oneshot service that exits non-zero enters the failed state, and the failure is stored until the next successful start or a reset.
systemctl status backup.service
systemctl --failed
systemctl show backup.service -p Result -p ExecMainStatus
journalctl -u backup.service -p err --since todayResult=exit-code and ExecMainStatus=1 tell you the script ran and failed. Result=timeout points at TimeoutStartSec. Result=signal means the process was killed.
By default, systemd only records the failure. It does not notify anyone. To get an alert, attach an OnFailure= unit that runs when the job fails.
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
OnFailure=notify-failure@%n.service
[Service]
Type=oneshot
User=backup
ExecStart=/usr/local/bin/backup.sh# /etc/systemd/system/[email protected]
[Unit]
Description=Send a failure alert for %i
[Service]
Type=oneshot
ExecStart=/usr/local/bin/notify.sh "%i failed"The %n specifier passes the failed unit's name to the template, and %i receives it as the instance name. Keep the notification script simple and free of dependencies on the failing job.
Scripts that must tolerate some failures
Sometimes a non-zero status is expected. grep exits 1 when it finds no match, and diff exits 1 when files differ. Under set -e these would stop your script. Handle them explicitly instead of turning off strict mode.
# grep returning 1 means "no match", which is fine here
count=$(grep -c "ERROR" app.log || true)
# Distinguish "no match" (1) from a real error (2)
rc=0
grep -q "ready" status.txt || rc=$?
if [ "$rc" -gt 1 ]; then
echo "grep failed with $rc" >&2
exit "$rc"
fiUse || true only where you have thought about which failures you are discarding. A blanket || true hides real errors, which defeats the purpose of strict mode.
Failing loudly in practice
A reliable job reports failure through at least two independent channels. A typical combination:
- The script exits non-zero and writes a clear message to standard error.
- The scheduler records or forwards the failure (
OnFailure=, or cron mail). - A heartbeat check, covered in a later chapter, alerts when the success signal is missing.
The third channel matters because the first two can themselves fail. If the machine is down, the script never runs, so it cannot report anything. Only an external check notices a missing success.
Place the success report last in the script, after all work has finished. The backup example in this tutorial pings its heartbeat URL only after mv completes. With set -e active, any earlier failure stops the script before that line, so the ping is sent only on real success.
Common errors
- Last-command masking. A script ends with
echoorlogger, which succeeds and hides an earlier failure. Useset -eor check statuses. - Missing pipefail. A pipeline stage fails but the final stage succeeds.
- Exit status lost in a wrapper.
cmd | tee logreturns the status ofteeunlesspipefailis set. Use${PIPESTATUS[0]}to read the first stage's status. - Trap overwriting. A second
trap ... EXITreplaces the first. Combine cleanup in one function. - Subshell failures. A failure inside
$( ... )used in an assignment such asx=$(cmd)is caught byset -e, butecho "$(cmd)"is not, because the status belongs toecho.
Exercise
A cron job runs pg_dump mydb | gzip > /var/backups/db.sql.gz and the script has set -e but not set -o pipefail. The database is down, so pg_dump fails. Does the script exit with an error, and what ends up in the backup file? What single line fixes the problem?
Show answer
The script does not exit with an error. Without pipefail, the pipeline's status is that of gzip, which succeeds, so set -e never fires. gzip compresses the empty output and writes a tiny, valid but empty archive over the previous good backup. Adding set -o pipefail (usually combined as set -euo pipefail) makes the pipeline fail when pg_dump fails, so the script stops. Writing to a temporary file and renaming it only on success also protects the old backup.
Exercise
A systemd oneshot service exits with status 1 every night, but nobody is told. Name the unit setting that sends an alert, and name two commands you can use to confirm the failure.
Show answer
Add OnFailure= to the [Unit] section, pointing at a notification unit such as notify-failure@%n.service. To confirm the failure, use systemctl status backup.service or systemctl --failed, and systemctl show backup.service -p Result -p ExecMainStatus. journalctl -u backup.service -p err shows the error output.