Script Valley
Linux & Bash for Developers
Advanced Bash & AutomationLesson 6.2

Bash error handling with set -e, set -u, and traps

set -e exit on error, set -u undefined variables, set -o pipefail, set -x debug mode, trap ERR, || true pattern, defensive scripting

Scripts Fail Silently Without Proper Error Handling

By default, Bash continues executing even after a command fails. A script that silently skips failed steps causes corrupted deployments and data loss. Three settings at the top of every production script eliminate this class of bug.

The Essential Three

#!/bin/bash
set -euo pipefail
# -e: exit immediately if any command returns non-zero
# -u: treat undefined variables as errors
# -o pipefail: a pipe fails if any command in it fails

# Without -u, this silently produces wrong output
echo "Deploying to: $DEPLOY_ENV"  # error if DEPLOY_ENV unset

# Without pipefail, this succeeds even if grep fails
grep "ERROR" app.log | wc -l

Handling Expected Failures

# Sometimes a command is allowed to fail
# Use || true to suppress exit on that specific command
rm -f temp_file.txt || true

# Or test explicitly
if ! cp source dest 2>/dev/null; then
  echo "Copy failed, using fallback"
  cp fallback dest
fi

trap ERR for Centralized Error Handling

#!/bin/bash
set -euo pipefail

error_handler() {
  local EXIT_CODE=$?
  local LINE=$1
  echo "ERROR: Script failed at line $LINE with exit code $EXIT_CODE" >&2
  # Send alert, cleanup, etc.
  exit $EXIT_CODE
}

trap 'error_handler $LINENO' ERR

echo "Starting deployment..."
rsync -avz ./dist/ user@prod:/var/www/  # if this fails, trap fires

Up next

Cron jobs: how to schedule tasks in Linux

Sign in to track progress

Bash error handling with set -e, set -u, and traps โ€” Advanced Bash & Automation โ€” Linux & Bash for Developers โ€” Script Valley โ€” Script Valley