Crontab

Open crontab

Use following command to open your user account’s crontab file. Commands in this file run with your user account’s permissions

crontab -e

To open crontab of root account, substitute user

su -c "crontab -e"

To edit other user crontab

crontab -u username -e

Note : change default editor before running command

Commands(MD)

Add Task in crontab

Adding New Tasks in that file

minute(0-59) hour(0-23) day(1-31) month(1-12) weekday(0-6) command

You can use an asterisk (*) character to match any value ( run the command /usr/bin/example at 12:30 a.m. every day)

eg:
29 0 * * * /usr/bin/example

Use comma-separated values to specific multiple times. (runs /usr/bin/example2 at the 15-minute mark on every hour, every day. Make sure you add each new task on a new line.)

0,14,29,44 * * * * /usr/bin/example2

Use dash-separated values to specify a range of values (runs /usr/bin/example3 at noon every day, but only in the first six months of the year.)

0 11 * 1-6 * /usr/bin/example3

Shorthands

use shorthands like @yearly, @monthly, @weekly, @daily, @hourly, @reboot (Run once, at startup.)

@daily /scripts/script.sh
//It will execute a task in the first minute of every day = “0 0 * * *”
@hourly /scripts/script.sh
// first minute of every hour = “0 * * * *”

View

To view crontab entries of current user

crontab -l

To to view crontab entries of the specified user.

crontab -u username -l

Note : (cron prefix file) logs are present in '/var/log/syslog' folder

To check cron is running

ps ax | grep cron

Logs

CentOs

//Syntax
vi /var/spool/mail/{user}
//example
vi /var/spool/mail/root
vi /var/log/cron

Custom

Copy command output to a file for debugging individually

* * * * * /path/to/prog var1 &>>/tmp/cron_debug_log.log

Usage of env variables

  • if env variables are used in executing script, then add bin bash line with -l option
#!/bin/bash -l
# -l in above line should pick up your bash environment variables for cron

Tips

  • Have proper permission on bash files to be executed by cron,
  • Let bash files have full path cd as first line (else path will be considered from home directory)
  • use -l option in bin/bash line if any env variables

Links