How to Automate Verified Linux Backups with Bash and systemd Timers
On this page
Backups that depend on someone remembering to run them eventually fail. This tutorial creates a nightly compressed backup with a checksum, automatic deletion of old archives and a scheduled run using a systemd timer.
Prerequisites
- Ubuntu 24.04 with
sudoaccess - A directory to protect (this guide uses
/srv/data) - Free space in
/var/backups/data, and a plan to copy archives off the machine
Step-by-Step Guide
Step 1: Create the backup script
Save this as backup.sh in your current directory.
#!/usr/bin/env bash set -euo pipefail SRC="/srv/data" DEST="/var/backups/data" KEEP_DAYS=14 STAMP="$(date +%F_%H%M%S)" ARCHIVE="backup-$STAMP.tar.gz" mkdir -p "$DEST" tar -czf "$DEST/$ARCHIVE" -C "$SRC" . ( cd "$DEST" && sha256sum "$ARCHIVE" > "$ARCHIVE.sha256" ) find "$DEST" -type f -name 'backup-*' -mtime +"$KEEP_DAYS" -delete echo "Backup complete: $ARCHIVE"
Step 2: Install and test it
sudo mkdir -p /srv/data sudo install -m 750 -o root -g root backup.sh /usr/local/bin/backup.sh sudo /usr/local/bin/backup.sh
Step 3: Create the systemd service
Create /etc/systemd/system/backup.service:
[Unit] Description=Daily directory backup [Service] Type=oneshot ExecStart=/usr/local/bin/backup.sh
Step 4: Create the timer
Create /etc/systemd/system/backup.timer:
[Unit] Description=Run the directory backup daily [Timer] OnCalendar=*-*-* 03:00:00 Persistent=true [Install] WantedBy=timers.target
sudo systemctl daemon-reload sudo systemctl enable --now backup.timer systemctl list-timers backup.timer
Persistent=true runs a missed backup after the machine was powered off.
Step 5: Test a restore
cd /var/backups/data sudo sha256sum -c backup-*.tar.gz.sha256 mkdir -p /tmp/restore-test sudo tar -xzf "$(ls -1 backup-*.tar.gz | tail -n 1)" -C /tmp/restore-test ls /tmp/restore-test
Conclusion
You now have scheduled, checksummed backups with 14-day retention. Keep a second copy off-site, check journalctl -u backup.service after changes, repeat the restore test every few months and never keep the only copy on the same disk as the original data.