Example: backup script
A complete, small backup script that puts the basics and best practices together, scheduled with cron under its own user.
Goal
Every night: pack /etc and /srv/app into a dated .tar.gz, keep the last 14 days, log the result. Built from Bash scripting basics and Script best practices.
The script
#!/bin/bash
# Purpose: nightly tar backup of config and app data, keeps KEEP_DAYS days
# Usage: backup.sh
# Runs as: root, via /etc/cron.d/backup (needs to read /etc)
set -euo pipefail
readonly SOURCES=(/etc /srv/app)
readonly DEST="/srv/backups"
readonly KEEP_DAYS=14
readonly ARCHIVE="${DEST}/backup-$(hostname)-$(date +%F).tar.gz"
log() { logger -t backup "$*"; echo "$(date '+%F %T') $*"; }
exec 9>/run/lock/backup.lock
flock -n 9 || { log "already running, exit"; exit 1; }
mkdir -p "$DEST"
log "creating $ARCHIVE"
tar -czpf "$ARCHIVE" "${SOURCES[@]}"
log "deleting backups older than $KEEP_DAYS days"
find "$DEST" -name "backup-*.tar.gz" -mtime +"$KEEP_DAYS" -delete
log "done, size: $(du -h "$ARCHIVE" | cut -f1)"
What each part does:
set -euo pipefail: stop on the first error, so a brokentarnever reaches the cleanup step.readonlysettings at the top: change them in one place.SOURCES=(...)is an array;"${SOURCES[@]}"passes every entry as its own argument.logger -t backupwrites to the journal:journalctl -t backup.flockstops a second run while the first is still busy.find ... -deletehandles retention. Test it once without-deleteto see what would be removed.
Install and test
sudo chmod 750 /usr/local/bin/backup.sh
shellcheck /usr/local/bin/backup.sh # should report nothing
sudo /usr/local/bin/backup.sh # run once by hand
ls -lh /srv/backups/
Schedule it
# nightly at 02:30
30 2 * * * root /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
This job runs as root because it must read all of /etc. A job that only backs up app data should run as its own user that owns that data. See Cronjobs.
Check that it ran
journalctl -t backup --since yesterday
tail /var/log/backup.log
Note: A backup on the same disk doesn’t protect against disk failure. Copy the archives to another machine (e.g. add
rsync -a "$DEST/" backup-host:/backups/$(hostname)/at the end), and test a restore now and then:tar -tzf ARCHIVElists the contents,tar -xzf ARCHIVE -C /tmp/restore-testrestores to a test folder.