Brief Introduction To Using Cron in Linux
By Diwanshu Shekhar
- 2 minutes read - 302 wordsCron is a system daemon used to execute desired tasks (in the background) at designated times.
A crontab is a simple text file with a list of commands meant to be run at specified times. It is edited with a command-line utility. These commands (and their run times) are then controlled by the cron daemon, which executes them in the system background.
crontab -e : opens an editor to edit the crontab file
The data that need to be entered in this file should follow the following format:
minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command
Examples
01 04 1 1 1 /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand
at 4:01am on January 1st plus every Monday in January
01 04 * * * /usr/bin/somedirectory/somecommand
The above example will run /usr/bin/somedirectory/somecommand
at 4:01am on every day of every month
45 04 * * * /usr/sbin/chkrootkit && /usr/bin/updatedb
The double-ampersand (&&
) can also be used in the “command” section to run multiple commands consecutively. The above example will run chkrootkit
followed by updatedb
at 4:45am daily - providing you have all listed apps installed. If chkrootkit
fails, updatedb
will NOT be run
Setting up environment variable
Cron job will not use the environment variables that are set up in the .bash_profile
file or the bashrc
file in the home directory of the user. If you are running a shell script with cron, type the following line before executing any other command in your shell script:
source /home/johndoe/.bash_profile
The above line will make all the user environment variables available to the cron job.
Debugging cron jobs
/var/log/cron
has logs of all cron jobs
Any output to stdout written during the runtime of your cronjob goes to /var/spool/mail/johndoe
Your crontab file is in the folder /var/spool/cron/johdoe