AI Hints
Home›Linux Tutorial›More Projects
Linux · Lesson 113 of 120

Project: Nightly Backup

With old backups removed.

⏱ 2 min read▶ Video at 2:31:20🎓 Free
Watch this lesson in the Linux courseWatch on YouTube ↗Full Linux course

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.

Project: Nightly Backup
From the video: Project: Nightly Backup
  • 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.

nano backup.shbash
#!/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.

Terminal
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.

keyvalue
0 2 * * *every night at 2
>> backup.log 2>&1log the output
head -n -7all but the last 7
Test restoresreally 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
Next up: Project: Disk Cleanup — find the space hogs