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:
*/1 * * * * env > /tmp/env
We obtain the variables used in the execution of Cron:
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:
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 .