Shell Script Error Handling and Logging in Bash

Handle errors gracefully in Bash: set -Eeuo pipefail and its gaps, trap ERR and EXIT, logger and journald, retries, flock and meaningful exit codes.

Aug 2, 2025 - 19:08
Nov 5, 2026 - 02:26
 0  101
TOPICDevOps BasicsPractical guide
Shell Script Error Handling and Logging in Bash

To handle errors gracefully in a shell script, turn on strict mode with set -Eeuo pipefail, catch failures with trap ... ERR and clean up with trap ... EXIT, check exit codes explicitly where a failure is expected, and send timestamped log lines to stderr, a log file, or the system journal with logger. Then exit with a meaningful status code.

This post is about production behaviour: what a script does when something goes wrong at 3 a.m. under cron, and what it leaves behind for the person reading logs the next morning. Finding bugs while you write a script is a different job, covered in our companion guide How to Debug Bash Scripts: set -x, ShellCheck, traps. Read that one for bash -x, PS4 and ShellCheck. Read this one to make the finished script fail safely and explain itself. Examples target Bash 4.4 or later, which every current Linux distribution ships.

Key takeaways

  • set -e stops on many failures but not all. It is ignored inside if conditions, && and || lists, and in parts of command substitutions. Know the gaps.
  • set -o pipefail makes a pipeline fail if any stage fails, not only the last one.
  • An EXIT trap is the reliable place for cleanup. An ERR trap is the place to log where the failure happened.
  • Send logs to stderr so stdout stays clean for data, and add timestamps and a severity on every line.
  • logger writes to the system journal, where journalctl -t yourtag finds the entries later.
  • Use distinct exit codes so cron, systemd or a CI job can tell kinds of failure apart.

Why the default behaviour is dangerous

By default Bash keeps going after a command fails. The classic example:

cd /srv/app/releases/old
rm -rf ./*

If the cd fails because the directory does not exist, the script carries on and deletes the contents of whatever directory it was already in. Unset variables have the same problem: rm -rf "$BUILD_DIR/" becomes rm -rf "/" if BUILD_DIR was never set (modern GNU rm refuses to remove / by default, but the same pattern hurts with any other path). Graceful error handling means the script notices these failures, stops before it does damage, tidies up, and records why.

Strict mode: what each option does

#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
OptionEffectWatch out for
-e (errexit)Exit when a simple command returns non-zeroIgnored in conditions, &&/|| lists and negated commands
-u (nounset)Treat unset variables as an errorUse ${VAR:-default} for optional variables and ${1:-} for optional arguments
-o pipefailA pipeline returns the last non-zero status of any stagegrep returning 1 for "no match" now fails the pipeline
-E (errtrace)Functions, command substitutions and subshells inherit the ERR trapWithout it, failures inside functions skip your ERR handler
IFS=$'\n\t'Word splitting only on newlines and tabsOptional; quoting variables properly matters more

The gaps in set -e

The Bash manual lists the cases where errexit does not fire. The ones that catch people most often:

set -e

# 1. Failure inside a condition is not fatal (by design)
if grep -q pattern missing.txt; then echo found; fi

# 2. Only the last command of an && list can trigger exit
false && echo "never printed"   # script continues

# 3. local hides the status of the command substitution
myfunc() {
  local out=$(false)            # status of 'local' is 0, no exit
  local out2; out2=$(false)     # this one exits
}

# 4. Command substitution in older Bash does not inherit -e
shopt -s inherit_errexit        # Bash 4.4+: make $( ) honour -e

The practical rule: rely on set -e as a safety net, and still check the status of commands whose failure you expect and want to handle.

Checking exit codes on purpose

Every command returns a status from 0 to 255. Zero means success. Handle the expected failures yourself instead of letting errexit kill the script with no context:

if ! cp "$src" "$dest"; then
  log_error "copy failed: $src -> $dest"
  exit 3
fi

# Capture a status without triggering errexit
status=0
curl -fsS "$url" -o "$tmp" || status=$?
if (( status != 0 )); then
  log_warn "download failed with curl exit $status, using cached copy"
fi

Pipelines and PIPESTATUS

With pipefail you know that a stage failed. PIPESTATUS tells you which one. Read it immediately, because the next command overwrites it:

set +e
pg_dump mydb | gzip > backup.sql.gz
codes=("${PIPESTATUS[@]}")
set -e
if (( codes[0] != 0 )); then log_error "pg_dump failed (${codes[0]})"; exit 4; fi
if (( codes[1] != 0 )); then log_error "gzip failed (${codes[1]})"; exit 5; fi

A logging function you can reuse

Good log lines answer four questions: when, how bad, which script, and what happened. Write them to stderr so a caller piping your stdout into another program does not receive log noise.

readonly SCRIPT_NAME=${0##*/}
LOG_LEVEL=${LOG_LEVEL:-INFO}

_log() {
  local level=$1; shift
  printf '%s [%s] %s[%d]: %s\n' \
    "$(date '+%Y-%m-%dT%H:%M:%S%z')" "$level" "$SCRIPT_NAME" "$$" "$*" >&2
}
log_debug() { [[ $LOG_LEVEL == DEBUG ]] && _log DEBUG "$@" || true; }
log_info()  { _log INFO  "$@"; }
log_warn()  { _log WARN  "$@"; }
log_error() { _log ERROR "$@"; }

Notice the || true in log_debug. Without it, the function returns 1 when debug is off, and under set -e a harmless log call would end the script.

Copying all output to a log file

To keep a full record while still printing to the terminal, redirect the script's own output once near the top:

LOG_FILE=/var/log/myjob/myjob.log
mkdir -p "${LOG_FILE%/*}"
exec > >(tee -a "$LOG_FILE") 2>&1

This uses process substitution, so it needs Bash, not sh. Rotate the file with logrotate so it does not grow without limit.

Logging to the system journal with logger

On systemd-based systems, logger sends a message to the journal (and to syslog if rsyslog is running). That puts your script's messages next to everything else on the host, with central retention and forwarding already handled.

logger -t backup-job -p user.info "backup started for $DB"
logger -t backup-job -p user.err  "backup failed: pg_dump exit 4"

# Later, read them back
journalctl -t backup-job --since today
journalctl -t backup-job -p err

The -t tag is what you search on, so keep it stable. The -p priority uses syslog facility and level names, defined in RFC 5424. If the script runs as a systemd service, plain stdout and stderr already go to the journal under the unit name, and journalctl -u myjob.service shows them. For collecting and shipping these logs across servers, see RHEL 10 Log Management: Best Practices.

DestinationBest forHow to read it
stderrInteractive runs, CI jobsTerminal or CI log viewer
Log file (via tee)Cron jobs on a single hostless, grep, logrotate
Journal (via logger or systemd)Server automation, central log shippingjournalctl -t TAG

trap: cleanup and failure context

EXIT trap for cleanup

The EXIT trap runs when the script ends for any reason: normal completion, exit, or errexit. Put temporary file removal, lock release and service restarts there.

tmpdir=$(mktemp -d)
cleanup() {
  local rc=$?
  rm -rf -- "$tmpdir"
  if (( rc != 0 )); then
    log_error "exiting with status $rc"
  fi
  exit "$rc"
}
trap cleanup EXIT

Capture $? on the first line of the handler. Any command you run before that changes it.

ERR trap for the failure location

The ERR trap fires whenever a command fails in a way that would trigger errexit. Bash exposes enough variables to report exactly where:

on_error() {
  local rc=$? line=${BASH_LINENO[0]} cmd=$BASH_COMMAND
  log_error "command '$cmd' failed with status $rc at ${BASH_SOURCE[1]}:$line"
}
trap on_error ERR

Combined with set -E, this catches failures inside functions too. You get one log line naming the command, its status and the line number, which is usually enough to start investigating without rerunning the job.

Signals

Trap INT and TERM if the script must stop cleanly when someone presses Ctrl+C or systemd stops the unit. Exit with 128 plus the signal number, the shell convention:

trap 'log_warn "interrupted"; exit 130' INT
trap 'log_warn "terminated"; exit 143' TERM

Retries for transient failures

Network calls, package mirrors and API rate limits fail briefly and then recover. Retrying with a delay turns a flaky dependency into a slower success instead of a failed job. Do not retry operations that are not safe to repeat.

retry() {
  local max=$1 delay=$2; shift 2
  local n=1
  until "$@"; do
    if (( n >= max )); then
      log_error "giving up after $n attempts: $*"
      return 1
    fi
    log_warn "attempt $n failed, retrying in ${delay}s: $*"
    sleep "$delay"
    (( n++ ))
    (( delay *= 2 ))
  done
}

retry 5 2 curl -fsS -o artifact.tar.gz "$ARTIFACT_URL"

Preventing overlapping runs with flock

A cron job that runs longer than its interval will start a second copy, and two copies writing the same files is its own kind of failure. flock from util-linux makes the second copy exit immediately:

exec 9>/run/lock/myjob.lock
if ! flock -n 9; then
  log_warn "another instance is running, exiting"
  exit 0
fi

The lock is released when the script exits and file descriptor 9 closes, even after a crash. Our post on cron limitations in high-scale Linux environments covers when to move such jobs to systemd timers instead.

Exit codes that mean something

Callers only see your exit status. Give each class of failure its own number and document it at the top of the script.

CodeConventional meaning
0Success
1General error
2Misuse of shell builtins or bad arguments (Bash convention)
3 to 125Free for your own meanings, such as 3 = config missing, 4 = dependency down
126Command found but not executable
127Command not found
128 + NTerminated by signal N (130 for SIGINT, 143 for SIGTERM)

systemd, cron wrappers and CI systems can then react differently: retry on 4, alert on 3, ignore 0.

Validating input before doing work

Many failures are cheaper to catch at the start. Check arguments, required commands and environment variables before the script changes anything:

usage() { echo "usage: $SCRIPT_NAME <database> <dest-dir>" >&2; exit 2; }
(( $# == 2 )) || usage

for cmd in pg_dump gzip aws; do
  command -v "$cmd" >/dev/null || { log_error "missing command: $cmd"; exit 3; }
done

: "${AWS_REGION:?AWS_REGION must be set}"
[[ -d $2 && -w $2 ]] || { log_error "destination not writable: $2"; exit 3; }

The ${VAR:?message} form exits with the message if the variable is unset or empty, which reads more clearly than a bare nounset failure.

A complete template

#!/usr/bin/env bash
# backup.sh: dump a database and upload it
# Exit codes: 0 ok, 2 usage, 3 config, 4 dump failed, 5 upload failed
set -Eeuo pipefail
shopt -s inherit_errexit

readonly SCRIPT_NAME=${0##*/}
_log() { printf '%s [%s] %s: %s\n' "$(date '+%F %T')" "$1" "$SCRIPT_NAME" "${*:2}" >&2;
         logger -t "$SCRIPT_NAME" -p "user.${1,,}" "${*:2}" || true; }
log_info() { _log info "$@"; }
log_err()  { _log err  "$@"; }

tmpdir=$(mktemp -d)
cleanup() { local rc=$?; rm -rf -- "$tmpdir"; (( rc == 0 )) || log_err "failed, status $rc"; exit "$rc"; }
trap cleanup EXIT
trap 'log_err "line ${BASH_LINENO[0]}: \"$BASH_COMMAND\" returned $?"' ERR

exec 9>/run/lock/"$SCRIPT_NAME".lock
flock -n 9 || { log_info "already running"; exit 0; }

(( $# == 1 )) || { echo "usage: $SCRIPT_NAME <db>" >&2; exit 2; }
db=$1
: "${BACKUP_BUCKET:?BACKUP_BUCKET must be set}"

log_info "dumping $db"
pg_dump "$db" | gzip > "$tmpdir/$db.sql.gz" || exit 4

log_info "uploading"
aws s3 cp "$tmpdir/$db.sql.gz" "s3://$BACKUP_BUCKET/$(date +%F)/" || exit 5

log_info "done"

Run it through ShellCheck before you deploy it. ShellCheck flags several of the pitfalls above, including local masking return values (SC2155).

Where to go next

Error handling is one part of writing automation people can trust. For script ideas to practise on, see 20 DevOps Scripts for Infrastructure Automation, and for text processing inside those scripts, Search and Parse Text in Linux with grep, awk and sed. Shell scripting, systemd and journald are covered with lab exercises in our Linux administration course, run in Kharadi, Pune and live online.

Frequently asked questions

What does set -euo pipefail do?

It makes Bash exit when a command fails (-e), treat unset variables as errors (-u), and fail a pipeline if any command in it fails (-o pipefail). Adding -E makes functions and subshells inherit the ERR trap.

Why does my script not exit on error even with set -e?

errexit is ignored for commands in if, while and until conditions, in && and || lists except the last command, after !, and where local or export hides a command substitution's status. Check those places explicitly.

What is the difference between trap ERR and trap EXIT?

The ERR trap runs each time a command fails in a way that would trigger errexit, so it suits logging the failing line. The EXIT trap runs once when the script ends for any reason, so it suits cleanup.

How do I log from a shell script to the system journal?

Use logger with a tag and priority, for example logger -t myjob -p user.err "message". Read the entries with journalctl -t myjob. Scripts run as systemd services also have stdout and stderr captured automatically.

Should log messages go to stdout or stderr?

Send logs to stderr. Keep stdout for the data your script produces, so other programs can pipe it without parsing log lines out of the result.

How do I find which command in a pipeline failed?

Read the PIPESTATUS array right after the pipeline. It holds the exit status of each stage in order. Copy it into another array immediately, because the next command overwrites it.

How can I stop a cron script from running twice at once?

Open a lock file on a spare file descriptor and call flock -n on it. If another instance holds the lock, flock fails and the script can exit cleanly. The lock is released automatically when the script ends.

Which exit codes should my script use?

Use 0 for success and 1 or 2 for general and usage errors. Pick numbers between 3 and 125 for specific failures and document them. Avoid 126, 127 and values above 128, which the shell reserves for its own meanings.

Official references

Interested in learning more?Get a callback from our training advisors.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0
Mridul I am a passionate technology enthusiast with a strong focus on DevOps, Cloud Computing, and Cybersecurity. Through my blogs at DevOps Training Institute, I aim to simplify complex concepts and share practical insights for learners and professionals. My goal is to empower readers with knowledge, hands-on tips, and industry best practices to stay ahead in the ever-evolving world of DevOps.