🛠 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
- Pack
~/documentsinto~/backups/docs-DATE.tar.gz, where DATE is today's date, asdate +%Fprints it (YYYY-MM-DD) - Keep only the 3 newest backups and delete the older ones, so the disk never fills up
- 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.