Intermediate · 25 min · practise every command in the built-in terminal

🛠 Project: Nightly Backup

Until now you typed commands one at a time. A real admin writes them into a script once and lets the machine run it — every night, without being asked.

Your job: a script that backs up ~/documents. There are already five old backups in ~/backups, one a week, made by hand.

What the script has to do

  1. Pack ~/documents into ~/backups/docs-DATE.tar.gz, where DATE is today's date, as date +%F prints it (YYYY-MM-DD)
  2. Keep only the 3 newest backups and delete the older ones, so the disk never fills up
  3. Run every night at 01:30, by itself

Building blocks

date +%F                                        # Today's date: YYYY-MM-DD
tar -czf ~/backups/docs-$(date +%F).tar.gz -C ~ documents   # $(…) puts a command's output into another
ls -t ~/backups/docs-*.tar.gz                   # Newest first
ls -t ~/backups/docs-*.tar.gz | tail -n +4      # Everything after the 3rd line: the old ones
ls -t ~/backups/docs-*.tar.gz | tail -n +4 | xargs -r rm   # …deleted (-r: not when there are none)

A script is a text file

nano ~/scripts/backup.sh          # Write it (the first line: #!/bin/bash)
chmod +x ~/scripts/backup.sh      # Allow it to run
~/scripts/backup.sh               # Run it
crontab -e                        # Schedule it

💡 Try each line by itself first, then put the working lines into the script. In cron, write paths in full (/home/student/… or ~/…) — cron doesn't start in your home folder.

Practice tasks

  1. Create the script ~/scripts/backup.sh — a bash script
  2. Make it executable
  3. Run it: it saves ~/documents as ~/backups/docs-DATE.tar.gz, with today's date
  4. Make it keep only the 3 newest backups, and run it again
  5. Make it run every night at 01:30

Commands in this lesson

Projects