Bash Error Handling Shell Script: trap, set -euo pipefail and Safe Wrappers

bash error handling shell script

Scripts that fail halfway through a backup or migration are worse than scripts that fail loudly at the start. This pattern combines set -euo pipefail with trap handlers so every run logs start time, failing line, and exit code — ideal for cron mail and monitoring.

What this script does

  • Enables set -euo pipefail for strict failure semantics
  • Logs the failing command and line number on ERR
  • Always logs script end and exit code on EXIT
  • Wraps any command or script path passed as an argument
  • Returns the wrapped command’s exit code for cron alerting

Prerequisites

  • Bash 4+ on Linux
  • Write access to /var/log or your log directory
  • Scripts you wrap must be executable

Step 1: Save the script

sudo nano /usr/local/bin/safe-run.sh
sudo chmod +x /usr/local/bin/safe-run.sh

Step 2: Full script (scroll to read)

safe-run.sh
#!/usr/bin/env bash
set -euo pipefail

LOG="/var/log/safe-run.log"
TARGET="${1:?usage: safe-run.sh /path/to/script [args...]}"
shift || true

log(){ echo "[$(date '+%F %T')] $*" | tee -a "$LOG"; }

on_err(){
  local ec=$?
  log "ERROR: command failed (exit $ec) at ${BASH_SOURCE[1]}:${BASH_LINENO[0]}: ${BASH_COMMAND}"
  return "$ec"
}

on_exit(){
  local ec=$?
  log "END ${TARGET##*/} exit=$ec"
  exit "$ec"
}

trap on_err ERR
trap on_exit EXIT

log "START ${TARGET##*/} $*"
exec "$TARGET" "$@"

Scroll inside the box to read the full script.

Step 3: Configure settings

  • LOG — append-only log file for all wrapped runs
  • Pass the target script as the first argument; remaining args are forwarded
  • Pair with email from cron: MAILTO= or your monitoring stack
  • See also our shell scripting guide for basics
Bash trap error handling shell script logging a failed command
Bash trap error handling shell script logging a failed command

Step 4: Test manually

sudo install -m 755 safe-run.sh /usr/local/bin/safe-run.sh
sudo safe-run.sh /bin/false; echo exit=$?
sudo tail -5 /var/log/safe-run.log

Schedule with cron

sudo crontab -e

Add:

0 2 * * * /usr/local/bin/safe-run.sh /usr/local/bin/mysql-backup.sh

Related tutorials

Terminal screenshot is an original illustration created for Gnome IT Solutions (blog.gnomeitsolutions.com).