Home » Linux » Test run cron entry

Test run cron entry

Posted by: admin November 30, 2017 Leave a comment

Questions:

I added a cron job recently, but made a mistake in the path while giving the command and hence, the job never succeeded. Is there some way to test the cron changes we have done?

Please note that I had indeed copied and pasted the command from my command line and it was just an stray keypress that caused this.

Answers:

This question has also been asked on serverfault and has garnered a couple additional answers

The following is a paraphrased version of Marco’s solution:
(Not sure if best ediquite is not providing a link only answer or not copying someone else’s solution)

Create a environment file with a temporary cron entry

* * * * *  /usr/bin/env > /home/username/cron-env

Then create a shell script called run-as-cron which executes the command using that environment.

#!/bin/sh

. "$1"
exec /usr/bin/env -i "$SHELL" -c ". $1; $2"

It is then used like this:

run-as-cron <cron-environment> <command>

e.g.

run-as-cron /home/username/cron-env 'echo $PATH'

Questions:
Answers:

When I want to test my cron jobs I usually set the interval very low and monitor the logs closely. When I am convinced the entry is correct, I set the interval back to a sane value.

For example, run job every two minutes:

*/2 * * * * echo "Hello World"

And the I run tail -f on my log file (/var/log/syslogon debian).

Questions:
Answers:

Joshua’s answer does not work for me. Two problems:

  • Variables in cron-env file are not exported (set -a needed).

  • Script is still tied to current tty (setsid needed).

The script run-as-cron should be

#!/bin/sh

. "$1"
exec setsid /usr/bin/env -i "$SHELL" -c "set -a; . $1; $2" </dev/null

Not enough rep’ to fix his answer or add a comment…