Robust Error Handling in Bash Cron Scripts
Shell & BashThe Problem
Bash scripts continue executing after errors by default. A failed command in the middle of your script doesn't stop execution, leading to corrupted data or partial completions.
The Solution
Use set -euo pipefail and trap to catch errors. Combine with CronRabbit to report the failure status and get alerted.
The set -euo pipefail Pattern
set -e exits on error, -u treats unset variables as errors, -o pipefail catches failures in piped commands. This is the foundation of reliable Bash scripts.
Using trap for Cleanup and Reporting
Use trap to catch EXIT signals. In the trap handler, check the exit code and send the appropriate CronRabbit ping.
Code Examples
Production-grade cron script
Bash#!/bin/bash
set -euo pipefail
PING_URL="https://ping.cronrabbit.com/your-id"
# Trap errors and report to CronRabbit
trap 'if [ $? -ne 0 ]; then curl -fsS -m 10 --retry 5 --retry-all-errors "$PING_URL/fail"; fi' EXIT
# Signal start for duration tracking
curl -fsS -m 5 --retry 3 --retry-all-errors "$PING_URL/start"
# Your job logic (any failure triggers the trap)
tar -czf /backup/data.tar.gz /data
aws s3 cp /backup/data.tar.gz s3://my-bucket/
rm /backup/data.tar.gz
# Signal success
curl -fsS -m 10 --retry 5 --retry-all-errors "$PING_URL"