The whole thing is about sixty lines of shell and a state directory. Below is a working version, the traps that make people abandon these scripts, and how to stop babysitting it.
1. Define what counts as a backup
Before any loop, decide the answer to four questions, because every false alarm traces back to one of them.
- Which folder? Use the absolute path of the folder your job writes to. Mount it read-only if you can; this script never writes to it anyway, but the mount makes that guarantee structural.
- Which files? A glob, not "everything".
**/*.zipor**/*.sql.gzif you know your formats. If you must take everything, exclude in-progress artifacts explicitly:*.tmp,*.partial,*.part, and any file your job renames into place when done. - Where does state live? A separate directory, never inside the watched folder. Otherwise your own snapshot file shows up as an unknown backup and you get to debug that at 3am.
- What is "too old" and "too small"? Age: one schedule period plus a margin — a daily job gets 26 hours, not 24, so a run that starts late does not page anyone. Size: a floor per file type, not 1 byte. A 40-byte gzip header is a valid gzip file and a useless backup.
export BACKUP_DIR=/srv/backups
export STATE_DIR=/var/lib/backup-watch
export MIN_SIZE_BYTES=1048576 # 1 MiB; tune per format
export MAX_AGE_HOURS=26
2. Snapshot the folder to a small file
One line, one row per file. Tab-separated so filenames with spaces survive.
find "$BACKUP_DIR" -type f \
! -name '*.tmp' ! -name '*.partial' ! -name '*.part' \
-printf '%P\t%s\t%T@\n' | sort > "$STATE_DIR/current.tsv"
%P is the path relative to BACKUP_DIR, so the state file stays valid if you ever move the folder. %T@ is the modification time as a Unix timestamp with fractional seconds.
Two portability notes: -printf is GNU find, so on macOS you need gfind from coreutils or a stat loop. And if your job uses rsync -a or cp -p, the mtime is preserved from the source — the freshness check below will then measure the age of the data, not the age of the backup. That is sometimes what you want and sometimes a constant false alarm. Know which one you have.
3. Turn the snapshot into findings
Per file: undersized, stale. Plus a set comparison for missing. No database, no daemon.
#!/usr/bin/env bash
set -euo pipefail
: "${BACKUP_DIR:?}" "${STATE_DIR:?}" "${ALERT_WEBHOOK_URL:?}"
MIN_SIZE_BYTES="${MIN_SIZE_BYTES:-1048576}"
MAX_AGE_HOURS="${MAX_AGE_HOURS:-26}"
mkdir -p "$STATE_DIR"
CURRENT="$STATE_DIR/current.tsv"
PREVIOUS="$STATE_DIR/previous.tsv"
FINDINGS="$STATE_DIR/findings.txt"
LAST_SENT="$STATE_DIR/last-sent.txt"
: > "$FINDINGS"
if [ ! -d "$BACKUP_DIR" ]; then
echo "mount $BACKUP_DIR is not a directory (unmounted?)" >> "$FINDINGS"
: > "$CURRENT"
else
find "$BACKUP_DIR" -type f \
! -name '*.tmp' ! -name '*.partial' ! -name '*.part' \
-printf '%P\t%s\t%T@\n' | sort > "$CURRENT"
if [ ! -s "$CURRENT" ]; then
echo "empty no files under $BACKUP_DIR" >> "$FINDINGS"
fi
fi
now=$(date +%s)
while IFS=$'\t' read -r path size mtime; do
age_h=$(( (now - ${mtime%.*}) / 3600 ))
if [ "$size" -lt "$MIN_SIZE_BYTES" ]; then
echo "undersized $path ${size}B" >> "$FINDINGS"
fi
if [ "$age_h" -gt "$MAX_AGE_HOURS" ]; then
echo "stale $path ${age_h}h old" >> "$FINDINGS"
fi
done < "$CURRENT"
if [ -f "$PREVIOUS" ]; then
comm -23 \
<(cut -f1 "$PREVIOUS" | sort) \
<(cut -f1 "$CURRENT" | sort) \
| sed 's/^/missing /' >> "$FINDINGS"
fi
sort -u "$FINDINGS" -o "$FINDINGS"
The missing-mount and empty-folder cases are the ones people forget. If the NFS mount is gone, find returns nothing and the script happily reports zero problems — except that the -d test catches it, and because $CURRENT is emptied while $PREVIOUS still lists yesterday's files, every backup also shows up as missing. Same for a folder that exists but is empty: it gets its own finding instead of a silent pass.
4. Alert on change, not on every run
This is the part that decides whether the monitor survives contact with your team. A daily "3 backups are stale" message that never changes is noise, and noise gets muted, and muted alerts are worse than none because you believe you are covered.
Keep the last message you sent. Send only when the current findings differ.
if ! cmp -s "$FINDINGS" "$LAST_SENT"; then
if [ -s "$FINDINGS" ]; then
jq -Rs '{text: .}' < "$FINDINGS" \
| curl -fsS -X POST "$ALERT_WEBHOOK_URL" \
-H 'Content-Type: application/json' --data-binary @-
else
jq -n '{text: "backup check: all clear"}' \
| curl -fsS -X POST "$ALERT_WEBHOOK_URL" \
-H 'Content-Type: application/json' --data-binary @-
fi
cp "$FINDINGS" "$LAST_SENT"
fi
cp "$CURRENT" "$PREVIOUS"
That works with Slack and Discord incoming webhooks, and with ntfy if you drop the JSON and POST the text body instead. The "all clear" message matters: without it, a channel that has been quiet for a week is indistinguishable from a monitor that stopped running.
5. Schedule it after the backup window
Run it after the job should have finished, and use a lock so a slow run cannot overlap with the next one.
# /etc/systemd/system/backup-watch.service
[Unit]
Description=Backup folder state check
After=network-online.target
[Service]
Type=oneshot
Environment=BACKUP_DIR=/srv/backups
Environment=STATE_DIR=/var/lib/backup-watch
Environment=ALERT_WEBHOOK_URL=https://hooks.example.invalid/services/XXX
ExecStart=/usr/bin/flock -n /run/backup-watch.lock /usr/local/bin/backup-watch.sh
# /etc/systemd/system/backup-watch.timer
[Unit]
Description=Daily backup folder check
[Timer]
OnCalendar=*-*-* 06:30:00
Persistent=true
RandomizedDelaySec=120
[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now backup-watch.timer
systemctl list-timers backup-watch.timer
journalctl -u backup-watch.service -n 50
If you prefer cron: 30 6 * * * BACKUP_DIR=/srv/backups ... /usr/local/bin/backup-watch.sh >> /var/log/backup-watch.log 2>&1. Persistent=true is the systemd equivalent of cron's catch-up, so a machine that was off at 06:30 still runs the check when it comes back.
6. Prove the monitor works
An untested monitor is a rumour. Copy three files into a scratch directory (use your own filenames below), aim ALERT_WEBHOOK_URL at a test channel or a throwaway endpoint, and drive each finding by hand:
mkdir -p /tmp/bk-test && cp /srv/backups/*.zip /tmp/bk-test/ # a copy, not the originals
export ALERT_WEBHOOK_URL=https://hooks.example.invalid/services/TEST
BACKUP_DIR=/tmp/bk-test STATE_DIR=/tmp/bk-state ./backup-watch.sh # baseline, all-clear
truncate -s 12 /tmp/bk-test/one.zip # undersized
mv /tmp/bk-test/two.zip /tmp/bk-test/two.zip.hidden # missing
touch -d '3 days ago' /tmp/bk-test/three.zip # stale
BACKUP_DIR=/tmp/bk-test STATE_DIR=/tmp/bk-state ./backup-watch.sh # three findings
BACKUP_DIR=/tmp/bk-test STATE_DIR=/tmp/bk-state ./backup-watch.sh # silent: nothing changed
The first run records the snapshot and sends an all-clear. The second sends the three findings. The third sends nothing, which is the behaviour you want in a real channel. Delete last-sent.txt and re-run to confirm the message comes back, then throw the scratch directory away.
Common mistakes
- Alerting on every run. Covered above, and it is the number one reason these scripts get deleted.
- Watching the newest file only. One fresh file plus six missing ones passes that check.
- Counting symlinks and temp files.
-type falready skips symlinks; add-Lonly if your job really writes through them. - Measuring age across a timezone or DST change. Timestamps are absolute, so this is usually fine — but a job that writes with a preserved mtime from a source in another zone is not. Compare against the filename date if your job embeds one.
- Checking while the backup is being written. A growing file can look "changed" mid-write and "undersized" for a few seconds. Exclude the in-progress suffix and schedule after the window.
- Running as the wrong user. A check under root against a folder with
700backup permissions succeeds while the actual restore user cannot read it. Run the check as the user who will restore. - Hashing multi-gigabyte archives every run. Size plus mtime is enough for a daily change check; do the full content read only when something looks wrong.
- No record of what "normal" was. Without a baseline of paths and sizes you cannot distinguish "the job wrote a small file" from "this file has always been small".
Automating it
The script above covers the folder-level failures, but it has no memory of what a file looked like yesterday, no archive test, and no history you can open in a browser. Backup Integrity Drift Watch is a small self-hosted app that does exactly this job: it mounts your backup folder read-only, keeps a baseline of size and content for every file, and flags missing, late, undersized, changed and structurally corrupt archives — zip, gzip/tar and SQLite — on a 24-hour schedule. It alerts your webhook only when a status changes, exposes the current state as JSON at GET /api/backups, and stores nothing but metadata on your own server. Install is one Docker command, and the first scan of your mounted folder becomes the baseline.