HANDS-ON LAB Intermediate

Linux Backups with rsync & Hard Links: Daily Incremental Snapshots & Restore Drill

Building lightweight incremental snapshot backups using rsync --link-dest, automated checksum verification, and disaster recovery drills.

Vibe DevOps·· ~10 min read
LinuxBashrsyncflocksha256sumsystemd timer

Key Takeaways & Prerequisites

  • Rsync --link-dest creates point-in-time snapshot backups where unchanged files are hard-linked to the previous backup, consuming zero additional disk space.
  • Each daily snapshot behaves as a full, independent directory tree: restoring a backup requires only a simple cp or rsync command without merging diffs.
  • Atomic directory swaps prevent partial or corrupted backups from being treated as valid restore targets.
  • Automate retention with find -maxdepth 1 -mtime +N -exec rm -rf {} to prune aged snapshots safely while preserving shared hardlink data.

Architecture & Execution Flow

  1. 01 →Hardlink Deduplicationrsync --link-dest reference
  2. 02 →Atomic Directory Swapmv staging to completed timestamp
  3. 03 →Instant Full RestoreDirect access without delta merge
  4. 04 →Safe Snapshot PruningHardlinks preserve active data
Table of Contents

Application configuration and upload directories are frequently backed up via a crontab entry like rsync -a /data/ /backup/data/. This approach introduces two critical points of failure. First, the destination is overwritten on every run: if a file is accidentally deleted on Monday and only noticed on Wednesday, it has already been purged from the backup. Second, without regular restore drills, backup recoverability remains unverified.

This lab implements a lightweight script that resolves both challenges: every execution creates a point-in-time snapshot, consumes disk blocks only for incremental changes, computes cryptographic checksums for data integrity verification, and provides a practiced restoration procedure.

Scope: This lab runs under an unprivileged user account in $HOME/backup-lab, generates approximately 10 MB of dummy data, requires no root access, and uses no cloud infrastructure. The backup, retention, and restore workflows have been verified on Ubuntu 22.04 with rsync 3.2.7; the systemd unit files are validated with systemd-analyze verify without being enabled as an active scheduler. Production deployment steps are provided as guidance and must be validated against your own infrastructure.

Three primary patterns exist for single-server file-level backups:

  • Single-target overwrite via rsync. Advantage: Simplicity. Drawback: Single point-in-time recovery; accidental deletions or data corruption propagate to the backup on the subsequent run.
  • Daily compressed archives via tar.gz. Advantage: Self-contained, portable single-file artifacts. Drawback: Linear storage consumption per run; granular single-file restores require decompressing the entire archive.
  • Deduplication via rsync --link-dest. Advantage: Each snapshot functions as a browsable, standalone directory tree while unmodified files share underlying storage via hard links. Drawback: No native compression, no at-rest encryption, and strict reliance on hard link semantics.

Per the rsync documentation, --link-dest=DIR behaves like --copy-dest, but unchanged files are hard-linked from DIR into the destination directory. Files must match across all preserved attributes (permissions, timestamps, and ownership where applicable) to be linked.[1] As a result, each snapshot appears as a full copy, but only new or modified files consume additional disk blocks.

This architecture introduces several constraints: Hard links cannot cross filesystem boundaries. Because snapshots share underlying inodes, modifying a file directly inside a snapshot corrupts that file across all historical snapshots referencing that inode. Backup directories must be treated as strictly read-only. If your requirements mandate client-side encryption, compression, and block-level deduplication, tools like Restic or Borg are better suited; this lab focuses on native utilities available across standard Linux distributions.

2. Lab Setup

Prerequisites include Linux, Bash, rsync, flock (from util-linux), and sha256sum (from coreutils).

export LAB="$HOME/backup-lab"
mkdir -p "$LAB/data/config" "$LAB/data/uploads" "$LAB/snapshots"
cd "$LAB"
command -v rsync flock sha256sum
rsync --version | head -n 1

Generate mock data: configuration files and binary payloads simulating media uploads.

printf 'listen=127.0.0.1:8080\nlog_level=info\n' > "$LAB/data/config/app.conf"
printf 'user=demo\n' > "$LAB/data/config/users.conf"
head -c 8M /dev/urandom > "$LAB/data/uploads/video.bin"
head -c 1M /dev/urandom > "$LAB/data/uploads/avatar.bin"
du -sh "$LAB/data"

3. The Backup Script

Save the following script to $LAB/backup.sh. The script accepts three environment variables: SRC (source directory), DEST (snapshot root directory, absolute path required), and KEEP (retention count, defaults to 7).

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

SRC="${SRC:?SRC environment variable required}"
DEST="${DEST:?Cần đặt DEST (đường dẫn tuyệt đối)}"
KEEP="${KEEP:-7}"
MANIFEST=".backup-manifest.sha256"

case "$DEST" in /*) ;; *) echo "DEST phải là đường dẫn tuyệt đối" >&2; exit 2 ;; esac
[[ "$KEEP" =~ ^[1-9][0-9]*$ ]] || { echo "KEEP phải là số nguyên dương" >&2; exit 2; }
[ -d "$SRC" ] || { echo "Không thấy thư mục nguồn: $SRC" >&2; exit 2; }
mkdir -p -- "$DEST"

# Prevent concurrent backup runs targeting the same DEST.
exec 9>"$DEST/.lock"
flock -n 9 || { echo "Đang có lượt backup khác chạy" >&2; exit 75; }

stamp="$(date +%Y-%m-%dT%H%M%S)"
tmp="$DEST/.incomplete-$stamp"
final="$DEST/$stamp"
[ -e "$final" ] && { echo "Snapshot $stamp đã tồn tại" >&2; exit 1; }

link_opt=()
if [ -L "$DEST/latest" ] && [ -d "$DEST/latest" ]; then
  link_opt=(--link-dest="$(readlink -f -- "$DEST/latest")")
fi

rsync -a --numeric-ids --delete "${link_opt[@]}" -- "${SRC%/}/" "$tmp/"

# Checksum manifest for all files in the snapshot. The temp file resides
# outside the snapshot so find does not enumerate it.
(
  cd -- "$tmp"
  find . -type f ! -name "$MANIFEST" -print0 | sort -z | xargs -0 -r sha256sum
) > "$DEST/.manifest-$stamp.part"
mv -- "$DEST/.manifest-$stamp.part" "$tmp/$MANIFEST"

# Only completed snapshots receive a permanent name and the latest pointer.
mv -- "$tmp" "$final"
ln -sfn -- "$stamp" "$DEST/latest"
echo "OK snapshot: $final"

# Retain the KEEP most recent snapshots (timestamps allow lexical sorting).
mapfile -t snaps < <(find "$DEST" -mindepth 1 -maxdepth 1 -type d -name '20??-??-??T??????' -printf '%f\n' | sort)
excess=$(( ${#snaps[@]} - KEEP ))
for ((i = 0; i < excess; i++)); do
  rm -rf -- "${DEST:?}/${snaps[i]}"
  echo "Đã xóa snapshot cũ: ${snaps[i]}"
done

Implementation details:

  • "${SRC%/}/" guarantees a trailing slash on the source path. In rsync syntax, a trailing slash copies the contents of the directory rather than nesting the source directory inside the destination.[1]
  • --link-dest uses a canonical path resolved via readlink -f, preventing issues where rsync interprets relative paths relative to the destination directory.
  • flock -n fails fast if a lock is held rather than queuing operations.[2] Exit code 75 differentiates execution collisions from fatal rsync errors.
  • In-flight snapshots use the prefix .incomplete-, preventing retention rules from purging them prematurely and ensuring the latest pointer never targets a partial run.
  • Retention cleanup targets directory names matching the timestamp pattern inside DEST, avoiding unconstrained shell globs.
chmod +x "$LAB/backup.sh"
bash -n "$LAB/backup.sh" && echo "cú pháp OK"

Run the initial backup, modify a file, and execute a second backup:

cd "$LAB"
export SRC="$LAB/data" DEST="$LAB/snapshots" KEEP=3
./backup.sh
sleep 1
printf 'log_level=debug\n' >> "$LAB/data/config/app.conf"
./backup.sh
ls -l "$DEST"

Verify that the unchanged binary file shares an inode across snapshots. The first column shows the inode number, and the second displays the hard link count:

find "$DEST" -name video.bin -printf '%i %n %p\n'
find "$DEST" -name app.conf -printf '%i %n %p\n'
du -sh "$DEST"/20*
du -sh "$DEST"

Expected output: The two video.bin entries share an identical inode number with a link count of 2. The app.conf entries show different inodes due to the payload mutation. When calculating multiple directories in a single command, GNU du counts hard-linked files only once.[3] The initial snapshot reports ~9 MB, the second reports a few kilobytes, and the aggregate directory footprint (du -sh "$DEST") remains ~9 MB rather than doubling to 18 MB.

Verify the retention policy by running the script twice more with KEEP=3. After the fourth execution, the oldest snapshot is purged:

for n in 1 2; do sleep 1; ./backup.sh; done
find "$DEST" -mindepth 1 -maxdepth 1 -type d -name '20*' | wc -l

The output should report 3. video.bin remains intact across the retained snapshots; the underlying storage blocks are deallocated only when the final hard link referencing that inode is unlinked.

5. Restore Drill

Simulate an incident: accidental deletion of one file and corruption of another.

rm "$LAB/data/uploads/avatar.bin"
printf 'BROKEN\n' > "$LAB/data/config/users.conf"

Always verify snapshot integrity against the manifest before initiating a recovery:

cd "$DEST/latest" && sha256sum -c --quiet .backup-manifest.sha256 && echo "manifest OK"
cd "$LAB"

Next, perform a dry run using --dry-run and --itemize-changes to review the file operations rsync will execute. Do not use --delete during restoration unless you explicitly intend to purge all files created after the snapshot timestamp.

rsync -a --dry-run --itemize-changes \
  --exclude=.backup-manifest.sha256 \
  "$DEST/latest/" "$LAB/data/"

The output should show uploads/avatar.bin (flagged as >f+++++++++, indicating a new file transfer) and config/users.conf (>f.st......, indicating size and timestamp deltas). Lines prefixed with .d..t...... indicate directory timestamp updates. Once validated, execute the restore and verify the reconstructed state:

rsync -a --exclude=.backup-manifest.sha256 "$DEST/latest/" "$LAB/data/"
cd "$LAB/data" && sha256sum -c --quiet "$DEST/latest/.backup-manifest.sha256" && echo "restore OK"
cd "$LAB"

To restore an individual file from a specific point in time, copy it directly from that snapshot directory: cp -a "$DEST/<timestamp>/config/app.conf" /tmp/. This browsable layout allows data recovery without specialized extraction tooling.

6. Scheduling with systemd Timers (Reference Architecture)

This section provides a reference unit configuration. Syntax has been verified via systemd-analyze verify, but the timer is not enabled by default. Create two files in ~/.config/systemd/user/. File: backup-lab.service:

[Unit]
Description=Snapshot backup using rsync (lab)

[Service]
Type=oneshot
Environment=SRC=%h/backup-lab/data
Environment=DEST=%h/backup-lab/snapshots
Environment=KEEP=7
ExecStart=%h/backup-lab/backup.sh

File: backup-lab.timer:

[Unit]
Description=Run daily backup lab

[Timer]
OnCalendar=*-*-* 02:30:00
RandomizedDelaySec=15m
Persistent=true

[Install]
WantedBy=timers.target

Persistent=true records the timestamp of the last execution; if the host was offline when the timer was scheduled to trigger, the service executes immediately on boot. This directive only applies to OnCalendar= timers.[4] RandomizedDelaySec= introduces jitter to prevent thundering herd problems across fleets. Validate and inspect the units:

systemd-analyze verify ~/.config/systemd/user/backup-lab.service ~/.config/systemd/user/backup-lab.timer
systemctl --user daemon-reload
systemctl --user enable --now backup-lab.timer
systemctl --user list-timers backup-lab.timer
journalctl --user -u backup-lab.service -n 20

User timers execute only while the user session remains active. In production, enable systemd user lingering (loginctl enable-linger <user>) for service accounts, or convert the configuration into a system unit assigned to a dedicated service user with read-only access to source paths.

7. Troubleshooting & Common Failure Modes

  • New snapshots consume full duplicate capacity: The DEST path resides on a different filesystem than the prior snapshot, or file metadata (permissions, ownership) changed between runs. Debug using stat and review the --link-dest rules in the rsync manual.[1]
  • Exit code 75: A previous backup process is still running or holds the lock. Do not delete the .lock file; locate the process holding the file descriptor using ps or the unit's journalctl stream.
  • rsync exits with code 24: A file vanished during synchronization. This occurs when backing up active application runtime directories. For databases, avoid copying live data files directly; generate a consistent logical or physical dump first, then back up the export artifact.
  • Stale .incomplete-* directories or .manifest-*.part files: A previous run terminated abruptly. Diagnose the root cause, then manually remove only the matching orphaned artifacts.
  • sha256sum -c returns FAILED: The snapshot was modified or underlying disk corruption occurred. Do not restore from this snapshot; roll back to a prior point in time and run diagnostics on the storage layer.

8. Production Hardening and Teardown

Before deploying to production, address three intentional trade-offs in this lab: Isolate the snapshot volume onto separate physical storage or a dedicated backup host—a disk failure or catastrophic system wipe destroys backups stored on the local disk. Maintain at least one off-site replica (3-2-1 backup strategy); when using cloud object storage, model storage lifecycle costs and data egress fees incurred during recovery. Finally, operationalize regular restore drills (Section 5) and track your Recovery Time Objective (RTO).

Teardown: If the user timer in Section 6 was enabled, stop and remove the units:

systemctl --user disable --now backup-lab.timer 2>/dev/null || true
rm -f ~/.config/systemd/user/backup-lab.service ~/.config/systemd/user/backup-lab.timer
systemctl --user daemon-reload
rm -r -- "$HOME/backup-lab"

This lab installs no system packages, modifies no files under /etc, and provisions zero cloud resources.

Conclusion

An effective backup strategy answers three fundamental questions: What recovery points exist, which snapshots are verified intact, and how long does restoration take? rsync --link-dest provides point-in-time snapshots with low storage overhead, flock and .incomplete directories prevent partial writes, SHA-256 manifests guarantee data integrity, and structured restore drills validate RTO. If your application runs in containers, see our guide on Docker Compose with healthchecks and volumes to identify critical state paths. If backup storage capacity spikes unexpectedly, consult troubleshooting unlinked open files and disk space to identify root causes.

References

Verified on October 23, 2026:

[1] https://download.samba.org/pub/rsync/rsync.1 — rsync(1), --link-dest, trailing slash syntax, --itemize-changes [2] https://man7.org/linux/man-pages/man1/flock.1.html — flock(1), util-linux [3] https://www.gnu.org/software/coreutils/manual/html_node/du-invocation.html — GNU coreutils, du and hard links [4] https://www.freedesktop.org/software/systemd/man/latest/systemd.timer.html — systemd.timer, OnCalendar=, Persistent=, RandomizedDelaySec= [5] https://www.gnu.org/software/coreutils/manual/html_node/sha2-utilities.html — GNU coreutils, sha256sum

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs