ArunNetworkingPro
⏰

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.

Intermediate1 eveningBash & cron
🕑2:00 ambackup.sh🗂️7 days keptyou: 😴 your computer: 💪

🧰 What you need

Let's build it

1

Something worth saving

mkdir -p ~/important ~/backups
echo "do not lose me" > ~/important/notes.txt
2

Write 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.sh
3

Test it by hand

~/backup.sh
ls -lh ~/backups
4

Hand it to cron

crontab -e

Pick an editor if asked (nano is easiest), then add this line at the bottom:

0 2 * * * $HOME/backup.sh >> $HOME/backups/backup.log 2>&1

That reads: minute 0, hour 2, every day, every month, every weekday. In other words, 2:00 every night.

5

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