← All lessons
System administration · Lesson 7 of 7

Scheduled jobs and backups

cron runs commands on a schedule. Each user has a crontab, a list of jobs: crontab -e edits yours and crontab -l lists it. Each line is five time fields and then the command.

# minute hour day-of-month month day-of-week  command
30 2 * * *   /home/sam/bin/backup.sh
*/15 * * * * /home/sam/bin/check-site.sh
0 9 * * 1    /home/sam/bin/weekly-report.sh

A * means every. So the first line runs at 2:30 every night, the second every 15 minutes (*/15), and the third at 9:00 every Monday (day of week 1; Sunday is 0). Lists and ranges work too: 0 8-18 * * 1-5 is on the hour from 8 to 6, Monday to Friday.

cron runs jobs with a very short PATH and no terminal, so use full paths to commands and files, and send the output somewhere you can read it: 30 2 * * * /home/sam/bin/backup.sh >> /home/sam/backup.log 2>&1. The 2>&1 sends errors to the same place as the output.

Backups are the most important job of all. rsync -a copies a folder keeping permissions and dates, and on later runs copies only what changed, so it's fast. --delete also removes files that were deleted from the source, making an exact mirror. For a dated snapshot, tar czf /backups/site-$(date +%F).tar.gz /var/www/site makes a new archive each day.

A backup only counts if it's somewhere else and you've tried restoring from it. Keep a copy off the machine (another server, or cloud storage), and now and then restore a file to prove it works. A mirror alone isn't enough: if a file is deleted or wrecked, --delete copies the damage on its next run.

Practice

Open your crontab to edit it.

More info

Quick reference

crontab -e, crontab -lEdit or list your scheduled jobs.
min hour day month weekdayThe five fields; * means every.
*/15, 1-5, 0,30Every 15; a range; a list.
>> log 2>&1Save output and errors to a log.
rsync -a [--delete] src/ dst/Copy changes (mirror exactly).
tar czf name-$(date +%F).tar.gz dirA dated archive.

The other Linux courses