Practical computer tips, with a smattering of digital philosophy
Cron jobs not running properly? Check your paths (and other troubleshooting ideas)
January 3, 2012Posted by on
It took me several hours of poking around to figure out why certain cron jobs were quietly failing to run, while others (which were seemingly far more complex) were running just fine. The answer, it turns out, was sitting squarely in the middle of the manpage on crontabs (man 5 crontab):
Several environment variables are set up automatically by the cron(8) daemon. SHELL is set to /bin/sh, and LOGNAME and HOME are set from the /etc/passwd line of the crontab’s owner. PATH is set to “/usr/bin:/bin”
What this means is that even if a certain executable runs just fine from your own command prompt, cron may not know where to find it, because most user shells have PATHs far more extensive than the bare-bones default relied on by cron. And if cron cannot find an executable, it simply won’t run the task in question. There are two solutions to this problem. First, you can tell cron to check all of the paths that are active in your own shell session (issue: echo $PATH at a terminal, then put the results of that command on its own line at the top of your crontab file, like so:
PATH = <what you just got from echo $PATH>
Alternatively, you can just make sure to always use absolute pathnames for every exectuable you invoke in your crontab. To find the exact location of an executable, issue whereis <simple name of executable>.
Should you run into other problems getting your cron jobs to run (which is likely, given that any flaw in syntax anywhere in a crontab line can result in the entire line silently failing to execute), you can use output and error redirection to force the line in question to dump more information about why it’s failing to a specified location (basically, you’re creating your own mini-logging system). Set up such a log, and then try running the troublesome task every minute (* * * * *) until you get it to work.