Project: Nightly Backup
With old backups removed.
Daily backups are great, until the disk fills up with hundreds of them. A good backup script makes today's backup, and then deletes the old ones, keeping just the last week.

- Daily backups pile up
- Make today's backup
- Keep just the last week
backup.sh
Set dash E stops on any error. We build today's file name, make the folder, and create the archive. The clever part is near the bottom. LS lists the backups, oldest first, because the dates sort in order. Head dash N minus seven means everything except the last seven, and X args RM deletes them.
#!/bin/bash
set -e
dest="$HOME/backups"
file="$dest/backup-$(date +%F).tar.gz"
mkdir -p "$dest"
tar -czf "$file" -C "$HOME" Documents
echo "Saved $file"
# keep only the newest 7 backups
ls "$dest"/backup-*.tar.gz | head -n -7 | xargs -r rm
echo "Backups kept: $(ls "$dest" | wc -l)"Running the backup
The backups folder already holds ten older backups. We run the script. It saves today's file, and deletes the four oldest. LS shows the result. Exactly seven backups, the newest one from today.
ls backups | wc -l 10 ./backup.sh Saved /home/sam/backups/backup-2026-01-05.tar.gz Backups kept: 7 ls backups backup-2025-12-30.tar.gz backup-2026-01-02.tar.gz backup-2026-01-05.tar.gz backup-2025-12-31.tar.gz backup-2026-01-03.tar.gz backup-2026-01-01.tar.gz backup-2026-01-04.tar.gz
Making it nightly
Add one line to cron, and it runs every night, at two in the morning. Send its output to a log file, so you can check it worked. And remember the golden rule of backups. A backup you've never restored is just a hope. Test restoring it now and then.
| key | value |
|---|---|
| 0 2 * * * | every night at 2 |
| >> backup.log 2>&1 | log the output |
| head -n -7 | all but the last 7 |
| Test restores | really test them |
Summary
The backup script saves a dated archive, and keeps only the newest seven. Put it in cron, and log its output. Next, finding the big files that eat your disk.
Key takeaways- tar -czf backup-$(date +%F)
- head -n -7 | xargs rm
- cron at 2 am