tar backup script: backups with a log and automatic deletion of old archives

,

In many cases you do not need big backup software: a short Bash script using tar backs up directories daily into a compressed archive, writes a log and deletes backups older than a set number of days.

The script

File /opt/backup/backup.sh:

#!/usr/bin/env bash
set -euo pipefail

DEST="/opt/backup/archive"         # where the backups go
NAME="server"                        # prefix of the archive name
SOURCES=(/etc /var/www /home)        # what gets backed up
EXCLUDES=(--exclude='*.tmp' --exclude='/home/*/.cache')
KEEP_DAYS=14                         # days

STAMP=$(date +%Y-%m-%d_%H%M)
ARCHIVE="$DEST/$NAME-$STAMP.tar.zst"

mkdir -p "$DEST"
echo "=== $(date '+%F %T') Backup starting: $ARCHIVE"

tar --zstd -cf "$ARCHIVE" "${EXCLUDES[@]}" "${SOURCES[@]}"
chmod 600 "$ARCHIVE"
echo "Size: $(du -h "$ARCHIVE" | cut -f1)"

echo "Deleting archives older than $KEEP_DAYS days:"
find "$DEST" -name "$NAME-*.tar.zst" -type f -mtime +"$KEEP_DAYS" -print -delete

echo "=== $(date '+%F %T') Backup finished"
sudo chmod 700 /opt/backup/backup.sh

What happens here?

  • set -euo pipefail – the script aborts on an error instead of carrying on with half a backup.
  • --zstd – compresses with zstd: considerably faster than bzip2 at a similar size. If you do not have zstd, use -z (gzip) and the extension .tar.gz.
  • chmod 600 – the archive contains, for example, /etc/shadow and must only be readable by root.
  • find … -mtime +14 -delete – deletes all matching archives that were modified more than 14 days ago. -print writes the deleted files to the log.

Tip: before the first real run, leave out -delete and use only -print to check what would be deleted.

Running it daily with cron

Use sudo crontab -e to add the following line (daily at 2:30 a.m., output is appended to the log):

30 2 * * * /opt/backup/backup.sh >> /var/log/backup.log 2>&1

Alternative: systemd timer

A timer catches up on missed runs if the machine was off at the scheduled time, and writes the output to the journal. /etc/systemd/system/backup.service:

[Unit]
Description=tar backup

[Service]
Type=oneshot
ExecStart=/opt/backup/backup.sh

/etc/systemd/system/backup.timer:

[Unit]
Description=Daily tar backup

[Timer]
OnCalendar=*-*-* 02:30
Persistent=true

[Install]
WantedBy=timers.target
sudo systemctl daemon-reload
sudo systemctl enable --now backup.timer
journalctl -u backup.service      # view the log

Restoring

# Show the contents
tar --zstd -tf server-2026-11-30_0230.tar.zst | less

# Restore a single directory into a test folder
mkdir /tmp/restore
tar --zstd -xf server-2026-11-30_0230.tar.zst -C /tmp/restore etc/nginx

Important: a backup on the same disk does not protect against a disk failure. The archives should additionally be copied to another system – for example encrypted with duplicity.

Originally published in 2009, completely revised in November 2026.