Defensive Bash scripting: 7 scripts for backups and disks
Almost every team has a backup script someone threw together on a Friday. It runs fine for months, until the destination disk fills up, the dump gets cut off halfway, or an empty variable turns a rm -rf "$DIR/" into a disaster. The problem isn’t Bash — it’s how we write it.
Defensive Bash scripting starts from a simple idea: your script will fail someday, so it should fail loudly, safely and recoverably. Below are seven scripts built for production, sharing a common foundation and the decisions that make them reliable.
The shared foundation: a header that protects you
Every script shares this header. It’s what separates a hobby script from one you can actually operate:
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
umask 077
exec 9>"/var/lock/$(basename "$0").lock"
flock -n 9 || { echo "Ya hay una instancia en ejecución"; exit 1; }
log() { logger -t "$(basename "$0")" -- "$*"; echo "$(date -Is) $*"; }
trap 'log "ERROR en línea $LINENO"; exit 1' ERR
Each line earns its place:
set -Eeuo pipefailhalts execution on errors, undefined variables and failures inside pipelines.umask 077keeps backups from being readable by any user.flockstops two overlapping runs from corrupting the same destination.trap ERRleaves a trail in the journal with the exact line of the failure.
If you want to dig deeper into the interpreter’s behavior, the official GNU Bash manual is still the definitive reference.
Script 1: directory backup with atomic writes
The classic mistake is leaving a corrupt file with a valid name. The fix is to write to a temporary file, verify it, and only then rename:
SRC="/srv/data"; DEST="/backup/data"; TS=$(date +%F_%H%M)
TMP="$DEST/.data_$TS.tar.zst.part"
tar --zstd -cf "$TMP" -C "$SRC" .
zstd -t "$TMP"
mv "$TMP" "$DEST/data_$TS.tar.zst"
( cd "$DEST" && sha256sum "data_$TS.tar.zst" > "data_$TS.tar.zst.sha256" )
log "Backup OK: data_$TS.tar.zst"
The mv within the same filesystem is atomic: no process will ever see a half-written backup. The checksum lets you catch silent corruption months later.
Script 2: consistent PostgreSQL dump
For databases, copying the data directory while it’s running is a losing bet. Use the native dump in custom format and verify it:
OUT="/backup/pg/db_$(date +%F_%H%M).dump"
pg_dump -Fc -h localhost -U backup appdb > "$OUT.part"
pg_restore -l "$OUT.part" > /dev/null
mv "$OUT.part" "$OUT"
log "Dump verificado: $OUT"
pg_restore -l reads the dump’s index; if the file is truncated, it fails and the trap logs it. Credentials don’t belong in the script: use ~/.pgpass with 600 permissions or, better yet, a dynamic manager as explained in secret management with OpenBao.
Script 3: rotation with a safety net
Deleting old backups is dangerous: if new backups stopped being generated, rotation will eventually wipe them all. This script enforces a minimum number of copies:
DEST="/backup/data"; KEEP_DAYS=14; MIN_KEEP=3
total=$(find "$DEST" -name 'data_*.tar.zst' | wc -l)
mapfile -t old < <(find "$DEST" -name 'data_*.tar.zst' -mtime +"$KEEP_DAYS")
if (( total - ${#old[@]} < MIN_KEEP )); then
log "Abortado: quedarían menos de $MIN_KEEP copias"; exit 1
fi
for f in "${old[@]}"; do rm -f -- "$f" "$f.sha256"; log "Eliminado $f"; done
This is the most important pattern in the series: a cleanup should never be able to empty out what it’s protecting. If that condition trips, you should get an alert, not a clean disk.
Script 4: safe cleanup of temp files and logs
Here the risks are empty variables and filesystem crossings:
TARGET="${1:?Indica el directorio}"
case "$TARGET" in /var/tmp/*|/srv/app/cache/*) ;; *) log "Ruta no permitida"; exit 1;; esac
find "$TARGET" -xdev -type f -mtime +7 -delete
find "$TARGET" -xdev -type d -empty -mindepth 1 -delete
journalctl --vacuum-size=500M
docker image prune -af --filter "until=168h"
Three defenses in a few lines: ${1:?} aborts if the argument is missing, the allowlist with case limits the blast radius, and -xdev stops find from jumping to another mount. If you don’t use Docker, drop the last line.
Script 5: space alert before it’s too late
A backup that fills the disk takes down the very app it’s meant to protect. Monitor usage and warn early:
THRESHOLD=85
while read -r use mount; do
if (( ${use%\%} >= THRESHOLD )); then
curl -fsS -X POST -d "{\"text\":\"$HOSTNAME: $mount al $use\"}" \
-H 'Content-Type: application/json' "$WEBHOOK_URL"
log "Alerta: $mount al $use"
fi
done < <(df --output=pcent,target -x tmpfs -x devtmpfs | tail -n +2)
Load WEBHOOK_URL from an environment file with restricted permissions. It’s also worth checking inodes with df -i, because a disk can be “full” with plenty of free space left.
Script 6: off-site copy without propagating deletions
A backup on the same machine isn’t a backup. Send copies to external storage, like an S3-compatible bucket or Backblaze B2, using rclone copy rather than sync:
rclone copy /backup/data remote:backups/data \
--include 'data_*.tar.zst*' --transfers 2 --retries 5 --log-file /var/log/rclone.log
log "Sincronización off-site completada"
The difference is key: sync also replicates deletions, so a local mistake could wipe your remote copy. With copy, remote retention is handled by the provider’s own lifecycle policies, independent of your server.
Script 7: automated restore test
An untested backup is a hypothesis. This script restores the latest archive to a temp directory and validates its integrity:
DEST="/backup/data"
WORK=$(mktemp -d)
trap 'rm -rf -- "$WORK"' EXIT
latest=$(find "$DEST" -name 'data_*.tar.zst' | sort | tail -n 1)
( cd "$DEST" && sha256sum -c "$(basename "$latest").sha256" )
tar --zstd -xf "$latest" -C "$WORK"
(( $(find "$WORK" -type f | wc -l) > 0 )) || { log "Restauración vacía"; exit 1; }
log "Restauración de prueba OK: $latest"
Run it weekly. It’s the only script that answers the question that matters: will I be able to recover?
Schedule them with systemd timers, not cron
Cron doesn’t know whether the script failed or whether the machine was even on. systemd timers do. A minimal service and timer:
# /etc/systemd/system/backup-data.timer
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.target
Persistent=true runs the pending job if the server was off at that time. With OnFailure= in the service unit you can fire off a notification, and journalctl -u backup-data gives you the full history without setting up log rotation separately.
Code quality: linting and reproducible deployment
Scripts are production code too. Run them through shellcheck on every change and wire it into your pipeline, as described in frictionless CI/CD with GitHub Actions. When you need to roll them out to dozens of machines, an Ansible role guarantees identical versions, just like in hardening 50 Linux servers with Ansible.
Before you sign off on any script, go through this checklist:
- Are all variables used in deletion paths validated?
- Do your quotes protect every expansion (
"$var")? - Is there a lock against simultaneous runs?
- Does a failure trigger a visible alert, not just a line in a log?
- Have you tested the full flow in a staging environment, including the disk-full case?
Conclusion: automating is half the job
These seven scripts share a philosophy: validate before acting, write atomically, delete within limits, and always verify. With a strict header, rotation with a minimum copy count, off-site copies and regular restore tests, you go from “I think I have backups” to “I know I can recover.”
Start with script 7. If you can’t restore what you already have, no other improvement matters. Then adapt the rest to your environment and let the timers handle the boring work while you sleep soundly.