Your computer works night shifts now
It works the night shift so you can sleep.
The best backup is the one you don't have to remember. You'll write a small bash script that zips up a folder with today's date on it, then hand it to cron, Linux's alarm clock, to run every night.
🧰 What you need
- Any Linux machine
Let's build it
Something worth saving
mkdir -p ~/important ~/backups
echo "do not lose me" > ~/important/notes.txtWrite the script
cat > ~/backup.sh <<'EOF'
#!/bin/bash
set -euo pipefail
stamp=$(date +%F)
tar -czf ~/backups/important-$stamp.tar.gz -C ~ important
# keep only the 7 newest backups
ls -1t ~/backups/important-*.tar.gz | tail -n +8 | xargs -r rm --
echo "backup done: $stamp"
EOF
chmod +x ~/backup.shTest it by hand
~/backup.sh
ls -lh ~/backupsHand it to cron
crontab -ePick an editor if asked (nano is easiest), then add this line at the bottom:
0 2 * * * $HOME/backup.sh >> $HOME/backups/backup.log 2>&1That reads: minute 0, hour 2, every day, every month, every weekday. In other words, 2:00 every night.
Check it's scheduled
crontab -l✅ How you know it worked
Tomorrow morning, ls ~/backups shows a new file with today's date, and backup.log says backup done. Can't wait until tomorrow? See below.
💥 Break it on purpose
Change the schedule to * * * * * (every minute), wait two minutes, and watch backups appear. Then check: are there ever more than seven? The clean-up line is doing its job. Put it back to 0 2 * * * before your disk fills up with backups of backups.
🧠 What's really going on
cron is a background service that wakes up every minute, checks everyone's crontab, and runs whatever is due. The five stars are minute, hour, day of month, month and day of week. set -euo pipefail makes the script stop on the first error instead of carrying on and pretending everything is fine. For a backup script, that honesty is exactly what you want.
← Back to all Linux labs · Stuck? Email me