Show contents
Chapter 5 of 6 · 25 min
Project: an automatic backup
By the end of this chapter, you'll be able to
- Create a compressed, dated archive of a folder with tar
- Keep only the N most recent archives (rotation)
- Check that an archive is readable before trusting it
- Schedule the script with cron and log its result
The specification
Folder to back up : data/ (on a real server: /srv/school)
Archives folder : backups/ (ideally on another disk)
Archive name : school-YYYY-MM-DD.tar.gz
Retention : the 7 most recent archives
If a step fails : message on standard error, exit code 1
Schedule : every night at 2:30, result in a log
The YYYY-MM-DD date format has a decisive advantage: the alphabetical order of the names is also the chronological order. Sorting the archives by name is enough to know which ones are the oldest.
A line in the log proves that the backup really happened tonight.
Text description of the animation
- The script refuses to continue if the source folder is missing: an empty archive would be worse than no archive.
- tar gathers and compresses the whole folder into a single dated file.
- We read the archive back: if it is corrupted, we know now, not on the day of the failure.
- Sorted names give the chronological order: we delete everything except the 7 most recent.
- A line in the log proves that the backup really happened tonight.
The script, step by step
We set the date in a variable: in the real script, it will be $(date +%F) (today's date in YYYY-MM-DD format); here, we choose it to simulate several nights.
set -euo pipefail
mkdir -p data/students data/admin backups
echo "Fatou's homework" > data/students/fatou.txt
echo "Term grades" > data/admin/grades.csv
backup() {
local day=$1
local archive="backups/school-$day.tar.gz"
[[ -d data ]] || { echo "ERROR: data folder missing" >&2; return 1; }
tar czf "$archive" data
tar tzf "$archive" > /dev/null || { echo "ERROR: unreadable archive" >&2; return 1; }
echo "OK $archive"
}
backup 2026-11-16
tar tzf backups/school-2026-11-16.tar.gz | sort
OK backups/school-2026-11-16.tar.gz
data/
data/admin/
data/admin/grades.csv
data/students/
data/students/fatou.txt
tar czf archive folder: creates an archive, compressed with gzip, in the given file;tar tzf archive: lists the contents (t) of a compressed archive. If it fails, the archive is corrupted.
Rotation
We simulate ten nights, then keep only the seven most recent archives:
set -euo pipefail
KEEP=7
for day in 07 08 09 10 11 12 13 14 15; do
tar czf "backups/school-2026-11-$day.tar.gz" data
done
echo "Before: $(ls backups | wc -l | tr -d ' ') archives"
ls -1 backups/school-*.tar.gz | sort -r | tail -n +$((KEEP + 1)) | while read -r old; do
rm -- "$old"
echo "deleted: $(basename "$old")"
done
echo "After: $(ls backups | wc -l | tr -d ' ') archives, from $(ls backups | sort | head -1) to $(ls backups | sort | tail -1)"
Before: 10 archives
deleted: school-2026-11-09.tar.gz
deleted: school-2026-11-08.tar.gz
deleted: school-2026-11-07.tar.gz
After: 7 archives, from school-2026-11-10.tar.gz to school-2026-11-16.tar.gz
sort -r puts the most recent first; tail -n +8 skips the first 7 lines and keeps everything else, that is the archives to delete. The -- in rm -- marks the end of options: a file name starting with a hyphen would not be taken as an option.
Schedule and log
The final script is installed in /usr/local/bin/backup.sh, made executable with chmod +x, then scheduled in the administrator's crontab (sudo crontab -e):
30 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
Finally, the 3-2-1 rule for truly safe backups: 3 copies of the data, on 2 different media, 1 of them outside the building (another server, a disk stored elsewhere, online storage). An archive on the same disk as the data does not protect against that disk failing.
Your turn
Worked exercise
Project: the complete backup script
Write the complete backup.sh script, which takes as arguments the source folder, the archives folder and the number of archives to keep (7 by default). It must: check its arguments, create today's archive, verify it, rotate, and print a result line. Test it with a fixed date.
Hint 1
${3:-7} is the third argument, or 7 if it is missing.Hint 2
$(basename "$source").Show the solution and common mistakes
cat > backup.sh <<'END'
#!/usr/bin/env bash
set -euo pipefail
fail() { echo "ERROR: $*" >&2; exit 1; }
[[ $# -ge 2 ]] || fail "usage: $0 SOURCE DESTINATION [NUMBER_TO_KEEP]"
source=$1
destination=$2
keep=${3:-7}
day=${DAY:-$(date +%F)}
[[ -d $source ]] || fail "source folder not found: $source"
mkdir -p "$destination"
name=$(basename "$source")
archive="$destination/$name-$day.tar.gz"
tar czf "$archive" -C "$(dirname "$source")" "$name"
tar tzf "$archive" > /dev/null || fail "unreadable archive: $archive"
ls -1 "$destination/$name"-*.tar.gz | sort -r | tail -n +$((keep + 1)) | while read -r old; do
rm -- "$old"
done
total=$(ls -1 "$destination/$name"-*.tar.gz | wc -l | tr -d ' ')
echo "$day OK $(basename "$archive") (archives kept: $total)"
END
chmod +x backup.sh
DAY=2026-11-17 ./backup.sh data backups 7
./backup.sh 2>&1 || true
2026-11-17 OK data-2026-11-17.tar.gz (archives kept: 1)
ERROR: usage: ./backup.sh SOURCE DESTINATION [NUMBER_TO_KEEP]
The DAY variable lets you test the script with a chosen date; without it, it takes today's date. tar's -C enters the parent folder before archiving, so the archive contains data/… and not the full path.
Common mistakes:
- Archiving with an absolute path (
tar czf … /srv/school): on restore, the files would be recreated at their original location, maybe overwriting the current files. - Rotating before checking the new archive: if it is broken, you just deleted a good archive to replace it with a bad one.
- Keeping the archives on the same disk as the data: a disk failure takes both.
Summary
- 1tar czf creates a compressed archive; tar tzf reads it back and detects a corrupted archive.
- 2A YYYY-MM-DD date in the name makes alphabetical order chronological.
- 3Rotation keeps the N most recent archives and deletes the others, after checking the new one.
- 4The script runs every night with cron and writes a log line on each run.
- 53-2-1 rule: three copies, two media, one outside the building, and tested restores.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.