Timesaving crontab Tips
Setting up a crontab
for running scripts on a schedule can be frustrating to debug. Usually, it boils down to cron's environment being different than your user's (i.e. PATH
issues).
Always Setup crontab "Variables"
Your crontab file is not a shell script, but it has a few special variables that you can setup the same way you would a shell script. Set these special variables up in every crontab file you work with. Future you will thank you for it.
a@b.com,b@b.com"
MAILTO="When your cron jobs have output, or, more importantly, when they fail, cron will send the output e-mail these addresses.
PATH="/usr/bin:/sbin:/bin"
Logged in to the user account whose crontab you're setting up, go ahead and echo $PATH
and copy those contents into the PATH
variable of your crontab. Remember, this isn't a real script file, so you can't implicitly append :$PATH.
After assigning PATH and MAILTO, setting up your crontab is much easier.
HOME="/path/to/app/root"
The HOME
variable tells which directory cron should execute the crontab commands from. Often times you'll have a user/crontab per project. If so, set the HOME
variable to your project's root directory to avoid long, absolute paths to scripts or from having to 'cd /path/to/app/root && ...'
for each job.
SHELL="/bin/bash"
Set the default shell to execute your commands from with the SHELL command. Like PATH, a safe bet is making this the same as your user's shell. Logged in as that user, run echo $0
to get an absolute path to your shell.
Still Stumped? Dump Your Environment
It's easy to redirect cron's environment variables to a temporary file, as seen on Stack Overflow. Tweak the following to run from your crontab in the near future:
30 08 * * * env > /tmp/cronenv
Once it runs, cat /tmp/cronenv
to see your crontab's environment variables. Alternatively, if you're getting cron error messages e-mailed to you after setting up MAILBOX
above, look at the raw headers of the e-mail. E-mails from cron should set X-CRON-ENV
headers with these environment variables, too.
Happy automating!