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.
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.
When your cron jobs have output, or, more importantly, when they fail, cron will send the output e-mail these addresses.
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.
MAILTO, setting up your crontab is much easier.
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.
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
which `echo $0` to get an absolute path to your shell.
Still Stumped? Dump Your Environment
It's easy to pipe 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.