Challenge: automate a nightly backup
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 sitels -l backupsWhat the script, ~/bin/backup.sh, should do:
- Stop at the first failure.
- Pack
~/siteinto~/backups/site-YYYY-MM-DD.tar.gz, with today's date in the name. - 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 -enear the top.date +%Fprints today's date as2026-01-12, so"site-$(date +%F).tar.gz"is today's name.tar -czf ARCHIVE -C ~ sitemakes a compressed archive ofsite;-C ~makes the paths inside start atsite/.tar -tzf ARCHIVElists what's inside.find ~/backups -name "site-*.tar.gz" -mtime +3 -deleteremoves the old ones. Run it without-deletefirst.mkdir -p ~/binmakes the folder for the script;chmod +xmakes 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.
Your task
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.
- ~/bin/backup.sh is executable and starts with set -e (not done yet)
- It makes today’s archive of the site (not done yet)
- It deletes the backups older than 3 days and keeps the rest (not done yet)
- cron runs it at 01:00 every night (not done yet)
- You ran it by hand: today’s backup is there (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
set -e- Exit when a command fails
tar- Pack files into an archive, or unpack one More on tar
date- Print the date and time More on date
find -mtime- Changed N days ago: +N more than N days ago, -N less than N days ago More on find
crontab- Schedule commands to run regularly (cron) More on crontab
Every everyday command on one page: the Linux commands cheat sheet.