The Analogy: The Off-Site Backup Vault and the Fire-Drill Restore
Every serious organisation keeps copies of its records somewhere other than the building that holds the originals. A courier calls each evening, collects a sealed box of that day's tapes or documents, and drives them to a vault on the far side of the city -- fireproof, climate-controlled, and run by people whose only job is to store boxes and hand them back on request. The point is not tidiness; it is survival. If the head office burns down on Friday night, Monday's business depends entirely on what is sitting in that vault.
The vault does not keep everything for ever. Space and cost force a retention schedule: daily boxes are kept for a week, the Friday box of each week for a month, the month-end box for a year, and everything older is shredded on a fixed rota. This is rotation. It is deliberate, written down, and automatic, so that the vault never fills up and the boxes that remain are exactly the ones worth keeping. A good schedule keeps enough history to recover from a mistake noticed late, without paying to store a decade of daily noise.
A backup script is that courier and that schedule in software. It bundles the source into a dated archive, files it alongside the previous archives, and prunes the oldest ones so that only a chosen number survive. The dating is what makes rotation reliable: name each archive so that sorting the names sorts them by age, and "delete all but the newest three" becomes a one-line operation with no clock-reading at all.
There is one failure that quietly defeats the whole arrangement, and every experienced operator has a story about it. The courier calls, the boxes are stored, the schedule is followed to the letter -- and nobody ever opens a box to check that what is inside can actually be read. Then the disaster comes, the vault is opened in earnest for the first time, and the tapes are blank, or mislabelled, or written in a format no surviving machine can read. The backups existed; the restore did not. A backup is not a backup until you have restored from it and seen the data come back intact, which is why the discipline includes a periodic fire drill: pull a random archive and prove it restores.
Syntax or Core Structure
The unit of a backup is an archive. tar bundles a directory tree into one file; with -z it is gzip-compressed, and -C makes the archived paths relative to the source so a restore does not recreate the whole absolute path. Listing the archive with -t shows what it holds:
mkdir -p src
printf 'alpha\n' > src/a.txt
printf 'beta\n' > src/b.txt
tar -czf backup.tar.gz -C src .
tar -tzf backup.tar.gz | LC_ALL=C sort
Output:
./
./a.txt
./b.txt
-c creates, -z compresses, -f names the file, and -C src . means "change into src and archive everything there," so the stored paths are ./a.txt rather than a long absolute path. The -t flag lists an archive without extracting it, and piping through LC_ALL=C sort gives a stable, locale-independent order suitable for comparison.
Technical Depth: Rotating and Verifying
Name archives so they sort by time
Rotation is only as reliable as the order you rotate in. If you decide which archives to delete by modification time, a restored or copied file with a fresh timestamp can push a genuinely old backup to the front and save the wrong one. Naming each archive with an ISO date -- backup-2024-01-05.tar.gz -- sidesteps the clock entirely: a plain lexical sort of the names is already chronological.
| Strategy | Order key | Fragile because |
|---|---|---|
ls -t by mtime | file modification time | a touch or copy rewrites mtime |
| ISO-dated names | the name itself | nothing, if the format is fixed |
| Keep newest N | count | silent if a day is skipped |
| Keep by age | date arithmetic | needs correct clock and timezone |
The ISO-name approach wins for scripts because it depends on nothing but the filenames, which the backup script controls. Fixing the width of every field -- four-digit year, two-digit month and day -- is what makes the lexical sort match the calendar.
Keep the newest N and prune the rest
With sortable names, "keep the newest three" is sort followed by head -n -3, which prints every line except the last three -- precisely the archives to delete:
KEEP=3
for d in 01 02 03 04 05; do : > "backup-2024-01-$d.tar.gz"; done
ls -1 backup-*.tar.gz | sort | head -n -"$KEEP"
Output:
backup-2024-01-01.tar.gz
backup-2024-01-02.tar.gz
The five archives sort oldest-first; head -n -3 drops the three newest and leaves the two oldest, which are exactly the ones to remove. If fewer than three archives exist, head -n -3 prints nothing and nothing is deleted -- the prune is safe on a young backup set.
A backup is not a backup until you restore it
Creating the archive is the easy half. The half that saves you is proving it can be read back. A round-trip test extracts the archive into a scratch directory and compares it with the source; diff -r is silent and returns success only when every file matches:
mkdir -p out
tar -xzf backup.tar.gz -C out
diff -r src out && echo "restore verified"
Output:
restore verified
diff -r walks both trees and prints nothing when they are identical, so the && fires and confirms the restore. Run this against a real archive occasionally -- the fire drill -- and a corrupt or truncated backup announces itself while you still have the original, instead of during an emergency when you do not.
Confirming an archive without unpacking it
tar -tzf lists an archive's contents, and sent to /dev/null it becomes a cheap integrity probe: to list the members it must inflate the whole gzip stream and read every header, so a truncated or corrupt archive makes it exit non-zero without writing a single file to disk.
tar -czf good.tar.gz -C src .
tar -tzf good.tar.gz >/dev/null && echo "ok: readable" || echo "bad: unreadable"
cp good.tar.gz bad.tar.gz
truncate -s 20 bad.tar.gz
tar -tzf bad.tar.gz >/dev/null 2>&1 && echo "ok: readable" || echo "bad: unreadable"
Output:
ok: readable
bad: unreadable
The good archive lists cleanly; the copy chopped to twenty bytes cannot be inflated, so tar fails and the guard reports it. This is the check to run right after writing an archive and before pruning the old ones: it is fast, it touches no files, and it catches the most common failure of all, a backup that never finished writing.
Restoring a single file
A restore is rarely "give me everything back." More often one file was deleted or clobbered and you want only that member. Naming the path exactly as it is stored in the archive -- with the leading ./ -- extracts just it and leaves the rest untouched:
mkdir -p out
tar -xzf good.tar.gz -C out ./b.txt
ls -1 out
cat out/b.txt
Output:
b.txt
beta
Only b.txt lands in out; the other members are skipped. The name must match what tar -tzf prints -- here ./b.txt, because the archive was built with -C src .. Guess the path wrong and tar reports "Not found in archive" and exits non-zero, which is why the integrity listing above doubles as the catalogue you restore from.
Leaving out what you never want to restore
Caches, build outputs, and scratch directories bloat an archive and can even overwrite fresher data on restore. --exclude drops matching paths before they are read, and the pattern is matched against the names tar would store, so with -C src . you exclude ./cache rather than the absolute path:
tar -czf out.tar.gz -C src --exclude='./cache' .
tar -tzf out.tar.gz | LC_ALL=C sort
Output:
./
./a.txt
./b.txt
The cache directory and everything under it never enter the archive, so the backup is smaller and a restore cannot resurrect stale cached files over good ones. Keep the exclude list in the script, next to the archive command, so every run is consistent: an exclude that lives only in someone's memory is an exclude that will be forgotten on the one run that matters.
Real World Example: A Rotating Backup Script
In practice the courier, the schedule, and the fire drill live in one script. backup.sh archives a source directory into a dated file, then prunes the directory of archives down to the newest KEEP. The date stamp defaults to today so a nightly cron job files one archive per day, and KEEP caps how many days of history the vault holds:
#!/usr/bin/env bash
# backup.sh -- archive SRC into DEST, then keep only the newest KEEP archives
set -euo pipefail
SRC="${1:?usage: backup.sh SRC DEST}"
DEST="${2:?usage: backup.sh SRC DEST}"
KEEP="${KEEP:-3}"
STAMP="${STAMP:-$(date +%F)}"
mkdir -p "$DEST"
archive="$DEST/backup-$STAMP.tar.gz"
tar -czf "$archive" -C "$SRC" .
echo "created $archive"
mapfile -t old < <(ls -1 "$DEST"/backup-*.tar.gz | sort | head -n -"$KEEP")
for f in "${old[@]}"; do
rm -f "$f"
echo "pruned $(basename "$f")"
done
echo "kept $(ls -1 "$DEST"/backup-*.tar.gz | wc -l) archive(s)"
Seed the vault with four older archives, then run the script for a fifth day with KEEP=3 (the STAMP is pinned here only to keep the output stable; in production it defaults to today's date):
STAMP=2024-01-05 KEEP=3 bash backup.sh site backups
Output:
created backups/backup-2024-01-05.tar.gz
pruned backup-2024-01-01.tar.gz
pruned backup-2024-01-02.tar.gz
kept 3 archive(s)
The new archive is written, the two oldest are pruned, and exactly three survive -- the rolling window the schedule promised. Point cron at this line each night and the vault maintains itself: one archive added, the oldest dropped, a fixed number always on hand.
Two weaknesses hide in this convenience. First, the script backs up whatever the source currently contains, good or bad, and rotation then works against you: if the source is silently corrupted and the fault goes unnoticed for KEEP runs, every healthy archive is pruned away and only corrupt ones remain -- rotation has faithfully destroyed your last good copy. A real system keeps some long-interval archives, a monthly that outlives the dailies, precisely so a late-discovered fault can still be undone. Second, and worse for a backup tool, the script never verifies what it wrote. tar -czf can report success and still leave an archive that will not extract -- a disk that filled mid-write, a file that changed as it was read -- and nothing here runs tar -tzf or a test restore to catch it. The script is a diligent courier that never once opens a box, which is the exact failure the analogy warned about; a production version would list or restore each fresh archive and refuse to prune until the new one has passed.
Common Mistakes
- Never testing a restore. An archive that was created without error can still be unreadable. Periodically extract a backup and compare it with a known source; a backup you have never restored is a hope, not a safeguard.
- Rotating by mtime instead of by name.
ls -torders by modification time, which a copy, restore, ortouchsilently rewrites, so the wrong archive gets kept. Name archives with fixed-width ISO dates and rotate on a lexicalsortof the names.
- Keeping only the newest N with no long-interval copy. If corruption goes unnoticed for N runs, rotation prunes every good archive. Keep a few weekly or monthly archives that outlive the dailies so a late-found fault is still recoverable.
- Backing up to the same disk as the source. A backup on the same volume dies with it when the disk fails. Copy archives to a different device or host, so a single hardware fault cannot take both.
- Archiving with absolute paths.
tar -cf a.tar /home/appstores the leading path and can overwrite live files on extraction. Use-C /home/app .so paths are relative and a restore lands where you choose.
- Ignoring
tarwarnings. "file changed as we read it" means the archive holds an inconsistent snapshot. Quiesce the source, snapshot it, or at least treat the warning as a failure rather than routing it to/dev/null.
- Not compressing, or compressing already-compressed data. Skipping
-zwastes space on text; re-gzipping JPEGs or video wastes CPU for nothing. Match the tool to the data instead of applying-zblindly.
- Pruning before the new archive is confirmed. Delete old archives, then fail to write the new one, and you have shrunk your safety net to nothing. Create and verify the new archive first, and prune only after it is known good.
- No off-host copy of the encryption key. If backups are encrypted and the only key lives on the machine that died, the archives are noise. Escrow the key somewhere independent of the data it protects.
Best Practices
- Test restores on a schedule. Automate a periodic extract-and-compare of a real archive so a broken backup is discovered as routine, not during a crisis.
- Name archives with fixed-width ISO dates.
backup-2024-01-05.tar.gzsorts chronologically by name, so rotation needs no clock and no metadata.
- Verify before you prune. List or restore each new archive and delete the old ones only once the new one is proven readable, so a failed backup never costs you the previous good ones.
- Keep tiers, not just a window. Retain some weekly and monthly archives alongside the dailies so corruption found late can still be reversed.
- Store a copy off the host. Push archives to another device, server, or region; a backup that shares the source's disk or datacentre shares its disasters.
- Make paths relative with
-C. Archive withtar -C SRC .so extraction cannot clobber unrelated absolute paths and a restore can target any directory.
- Fail loudly on
tarwarnings. Treat "file changed as we read it" and similar messages as errors; an inconsistent archive should stop the run, not slip by.
- Record what a restore requires. Note the tar options, any encryption key location, and the expected layout, so a stranger can recover the data without reverse-engineering the backup script.
Practice Exercises
- Round-trip proof. Write a script that archives a directory, extracts it into a scratch location, runs
diff -rbetween source and restore, and printsokonly on an exact match. Corrupt one byte of the archive and confirm the check now fails.
- Rotate by name. Create ten archives named
backup-2024-01-DD.tar.gzand write a one-liner that keeps the newest five and deletes the rest usingsortandhead -n -5. Verify that exactly the five oldest are removed.
- Verify-then-prune ordering. Extend a backup script so it lists the new archive with
tar -tzfand prunes old archives only if that listing succeeds. Simulate a truncated archive and show that nothing is pruned when verification fails.
- Tiered retention. Design a scheme that keeps seven daily, four weekly, and twelve monthly archives, and write the pruning logic for one tier. Explain in a comment how a fault discovered two months late could still be recovered.