Friday, October 15, 2010

Debugging the cronjobs

Cronjobs are famous to run successfully from shell but failing to run as a cronjob.
Well from my experience and looking at the issues at stackoverflow.com and superuser.com, I can say that there are mainly two issues:
  • cronjob have their own environment variables. for ex. they dont have PATH variables.
  • Other issues happen when you try to run a GUI app in a cronjob to give a high priority alert to a user.
So, basically you should always run a binary by giving its full path else its very likely that it will fail. You should also will have to the display when running a GUI app. For ex, to run a kdialog:
DISPLAY:0 /usr/bin/kdialog -title "Test" --msgbox "Test message" 
Well, that was just general guidelines. So, debug a cronjob, you can modify the cronjob code like:


#!/bin/bash
{
.
. 
#your actual code goes here
.
.
} >> /tmp/cronthatfailed.out 2>&1

That will actually redirect all the output to a file (/tmp/cronthatfailed.out) so that you can debug as to what happened. "2>&1" tells STDERR to redirect to STDOUT. Well, for information, in unix, 2 represents STDERR, 1 represents STDOUT and 0 represents STDIN.

So, that it. Next time your cronjob fail, just follow the above method. That always work for me.

No comments:

Post a Comment