This page looks best with JavaScript enabled

Debugging scripts in CRON

 ·  🎃 kr0m

In the FreeBSD handbook , we have specific instructions on how to configure Cron. In that same manual, we can find a very interesting section that shows how to execute a script/binary exactly as Cron would. This way, we can debug any type of problem.

First, we obtain the environment variables present in Cron by executing env and saving the output to a file:

crontab -e

*/1 * * * * env > /tmp/env

We obtain the variables used in the execution of Cron:

grep -e SHELL -e PATH -e HOME -e LOGNAME /tmp/env

LOGNAME=kr0m
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/kr0m/bin
HOME=/home/kr0m
SHELL=/bin/sh

Finally, we execute the script exactly as Cron would, so we can see if there is any problem:

env -i SHELL=/bin/sh PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/home/kr0m/bin HOME=/home/kr0m LOGNAME=kr0m PATH_TO_SCRIPT

Always, always, always execute the scripts in this way before adding them to crontab, as if we don’t, we may trust their execution and they may not actually work.

Another way to debug possible execution errors is to redirect the standard output and error to a log file:

# Script running from cron job, send ALL output to logfile
if [ "${TERM:-dumb}$PS1" == "dumb" ]; then
    LOG_FILE='/tmp/cron.log'
    > $LOG_FILE
    exec 2> $LOG_FILE # Redirect STDERR to logfile
    exec 1>&2 # Redirect STDOUT to STDERR
fi

If Cron requires any input from the user or performs any operation via SSH and the key is protected, we can always use Expect as we did in this previous article .

If you liked the article, you can treat me to a RedBull here