Skip to content

Challenge: automate a nightly backup

AdvancedLesson 49 of 6615 min

Put the Advanced level together: write a backup script with tar, date and find, make it safe with set -e, schedule it with cron and test it by hand.

Time to automate a real job. The website in ~/site should be backed up every night, and old backups should be cleared out so the disk doesn't fill up. There's more than one right way; the checklist runs your script on a fresh copy of these files and looks at the result.

ls site
ls -l backups

What the script, ~/bin/backup.sh, should do:

  1. Stop at the first failure.
  2. Pack ~/site into ~/backups/site-YYYY-MM-DD.tar.gz, with today's date in the name.
  3. Delete the backups older than 3 days, and keep the rest.

Then schedule it with cron for 01:00 every night, and run it once by hand to see it work.

Things you'll need:

  • set -e near the top.
  • date +%F prints today's date as 2026-01-12, so "site-$(date +%F).tar.gz" is today's name.
  • tar -czf ARCHIVE -C ~ site makes a compressed archive of site; -C ~ makes the paths inside start at site/. tar -tzf ARCHIVE lists what's inside.
  • find ~/backups -name "site-*.tar.gz" -mtime +3 -delete removes the old ones. Run it without -delete first.
  • mkdir -p ~/bin makes the folder for the script; chmod +x makes it executable.
  • In the crontab, the five fields for 01:00 every day are 0 1 * * *, and full paths are safest.

Try it:Test each line at the prompt before it goes in the script. A script is just commands you've already tried.

Your turn

Write ~/bin/backup.sh so that it stops at the first failure, packs ~/site into ~/backups/site-YYYY-MM-DD.tar.gz (today’s date), and deletes the backups older than 3 days. Make it executable, schedule it to run at 01:00 every night, and run it once by hand.

Next