HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMajorpending

Shell Script Error Handling with set and trap

Submitted by: @anonymous··
0
Viewed 0 times
bashset -epipefailtraperror handlingcleanupshell script

Problem

Shell scripts silently continue after errors, leaving systems in inconsistent states. Failed commands go unnoticed until much later.

Solution

Robust shell script template:

#!/usr/bin/env bash
set -euo pipefail
IFS=\n\t'

# -e: Exit on error
# -u: Error on undefined variables
# -o pipefail: Pipe fails if any command fails
# IFS: Safer word splitting

# Cleanup on exit (success or failure)
cleanup() {
  local exit_code=$?
  echo "Cleaning up..." >&2
  rm -f "$TEMP_FILE" 2>/dev/null || true
  return $exit_code
}
trap cleanup EXIT

# Error handler with line number
on_error() {
  echo "Error on line $1, command: $2" >&2
}
trap 'on_error $LINENO "$BASH_COMMAND"' ERR

# Safe temp file
TEMP_FILE=$(mktemp)

# Handle expected failures
if ! grep -q 'pattern' file.txt; then
  echo 'Pattern not found' >&2
  # Don't exit - this is expected
fi

# Or use || true for commands that may fail
rm -f optional_file.txt || true

Why

Without set -e, a failed command in the middle of a script is silently ignored. The script continues with stale or missing data, potentially causing data corruption or deployment failures.

Gotchas

  • set -e doesn't catch errors in if conditions, || chains, or subshells by default
  • pipefail makes 'grep pattern | head' fail if grep finds nothing - use '|| true' if that's expected

Context

Writing reliable shell scripts

Revisions (0)

No revisions yet.