I am new to cron and I want to test if cron's mailing stuff after an executed task and things like that work. Is there a more elegant way to test this, then setting a cron job to run every few seconds? So, is there any way to simulate the execution of a cron job / start a cron job manually, but with the same behaviour it would have when being run automatically by cron?
The main difference between executing a cron job on the command line and inside cron is its environment. Other potential differences include the current directory, the availability of a terminal, and which shell is used.
This is a fairly accurate simulation of running a cron job via cron. To avoid differences due to the shell, put your job in a script and put only the path to that script in the crontab. Note that the exact set and values of environment variables passed by cron are implementation-dependent; check the
Another way of creating a cron-like setting is through
Here is how I did it to simulate the cron execution of a script I've created years ago but which started failing recently.
I created a script called
This dumps all environment variables into a file in
This makes the script run every minute. So after a minute, I got a dump of the environment seen by tasks run from cron. If the crontab line is left to run more than a minute, it creates a bunch of identical files with names differing only in the pid part of the file name (
Then I created an additional file which I called
Then I issued:
And this replicated the fault I saw when my command is executed from cron. What
and executes it. The list of environment variables comes from the dump file. The command that
I do no explicit redirection of stdin to /dev/null because xargs does it for me. I also do not care about redirecting stdout/stderr, and I do not want to receive an email if the command fails. For cases where these features are desired, Gilles' answer provides the means to do it.
Louis' answer is great. I propose a slight possible improvement.
Instead of creating a file
Instead you can name the script directly in the command via the following alternate command (take note of the
This avoids any need to create a file