Automating your backups with cron

From docwiki
Jump to: navigation, search


Motivation

If you only do your backup when you hear about a case of someone loosing data then you will not have a recent backup when you need it. So you should automate the backup process. If you want to run a certain command at a regular interval then you can use the unix cron tool.

User and System Crontab

cron has a text based configuration file that contains the commands that should be run and when they should be run. There is a system crontab for all users and each user has his/her own crontab:

You can view this with
crontab -l

And edit it with:

crontab -e

which opens up your default editor. You can set a different editor with

export EDITOR=/usr/bin/yourfavoriteeditor

The system wide crontab can be found under /etc/crontab compared to the user contabs it has a slightly different format: After the block that specifies the time and before the command there is a field that contains the user that should be used to run this command. This field is not there in the user crontabs because each user can only run commands under their user-privileges there.

Example Crontab

53 3 * * * /root/meinbackup.sh >> /var/log/backup.log 2>&1
13 07 * * 0 /root/sonntagmorgens.sh
01,21,41 * * * * /root/3malprostunde
17 */3 * * 1-4 /root/8mal_mo-do.sh
# 0:17 3:17 6:17 .. each monday till thursday
30 7 1-24 12 * /root/advent.sh

The specification of the time when the job should be run consists of 5 fields:

minute hour day-of-month month day-of-week

An asterisk * matches any time. You can specify a range. E.g. Days 1-24 of the month or you can specify a list of values. E.g. minutes 1,21,41. Often you want to run every 3 hours or every 3 days: You can use */3 for that. Days are counted from sunday=0. But you can also use 7 for sunday.

Important Note on How to write your Cron Scripts

When you write a script that is used in a crontab you will normally try it out by hand before. You need to be aware that some things in your environment are different. E.g you do not have a graphical environment. Also the environment variables in will be different and maybe also the PATH variable. So either, set the PATH=... at the start of your script or specify explicit path of all commands that you use in your script.

Exercises

  • Look at the system crontab of your system.
  • add an entry in your user crontab that runs periodically and writes the date in a file in your homedirectory.
  • after you verified that it works: remove that entry above by placing a # at the start of the line.