Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in crontab?

Tags:

cron

How can I store variables in my crontab? I realize it's not shell but say I want to have some constants like a path to my app or something?

like image 966
JP Silvashy Avatar asked Sep 03 '10 20:09

JP Silvashy


People also ask

Can I use variables in crontab?

When we have a bash script in the crontab file, we can use the BASH_ENV variable. We set it with the path to a script, and bash will execute that script before running the job. This way, we can run a script, such as /etc/profile, to load the environment variables we need.

What does 0 * * * * mean in crontab?

0 * * * * -this means the cron will run always when the minutes are 0 (so hourly) 0 1 * * * - this means the cron will run always at 1 o'clock. * 1 * * * - this means the cron will run each minute when the hour is 1.

What are the fields of crontab?

Field Description Allowed Value MIN Minute field 0 to 59 HOUR Hour field 0 to 23 DOM Day of Month 1-31 MON Month field 1-12 DOW Day Of Week 0-6 CMD Command Any command to be executed.

How many fields are there in cron?

Linux Crontab format Crontab of Linux has six fields. The first five fields define the time and date of execution, and the 6'th field is used for command execution. Define range: Allows you to define a range with the help of hyphen like 1-10 or 30-40 or jan-mar, mon-wed.


2 Answers

In Vixie cron, which is possibly the most common, you can do this almost exactly like a shell script.

VARIABLE=value PATH=/bin:/path/to/doathing 0 0 * * * doathing.sh $VARIABLE 

The man page says:

An active line in a crontab will be either an environment setting or a cron command. An environment setting is of the form,

     name = value 

where the spaces around the equal-sign (=) are optional, and any subsequent non-leading spaces in value will be part of the value assigned to name. The value string may be placed in quotes (single or double, but matching) to preserve leading or trailing blanks. The name string may also be placed in quote (single or double, but matching) to preserve leading, trailing or inner blanks.

You can tell if you have Vixie cron by checking the man page for crontab; the author will be Paul Vixie. Different crons may or may not support this (BusyBox's cron for example, does not), in which case your best option is to wrap your command in a shell script and run that script from cron instead. In fact, this is a good thing to do for anything complicated.

like image 75
Matt K Avatar answered Sep 25 '22 08:09

Matt K


To keep my crontab clean, I would just call a shell script and do the fun stuff in the script.

like image 34
Justaman Avatar answered Sep 25 '22 08:09

Justaman