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

Shell script error handling and debugging

Submitted by: @anonymous··
0
Viewed 0 times
set -epipefailtraperror handlingdebuggingbash strict mode

Problem

Shell scripts silently continue after errors, making failures hard to detect and debug.

Solution

Robust error handling patterns:

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

# set -e: Exit on any command failure
# set -u: Error on undefined variables
# set -o pipefail: Catch errors in pipes

# Trap for cleanup on exit
cleanup() {
  echo "Cleaning up..."
  rm -f "$TMPFILE"
}
trap cleanup EXIT

# Trap for error reporting
on_error() {
  echo "Error on line $1, exit code $2" >&2
}
trap 'on_error $LINENO $?' ERR

# Safe temporary files
TMPFILE=$(mktemp)

# Explicit error handling for expected failures
if ! command -v docker &>/dev/null; then
  echo "Error: docker is not installed" >&2
  exit 1
fi

# Default values for optional vars
ENV=${ENV:-development}
PORT=${PORT:-3000}

# Debugging: uncomment to trace execution
# set -x

# Or trace a specific section
set -x
critical_operation
set +x

Why

Without set -euo pipefail, scripts continue executing after failures, potentially causing cascading damage with incorrect state.

Gotchas

  • set -e doesn't catch errors in command substitution: result=$(failing_cmd)
  • Pipes: only last command matters without pipefail

Context

Writing reliable shell scripts for CI/CD, deployment, or automation

Revisions (0)

No revisions yet.