Search code examples
bashcronstderr

cron job not running with adding "2>&1"


I am setting up a cron job using crontab -e on a machine where I do not have a root privilege.

The initial command in crontab is like this:

0 10 * * * /bin/bash /path/myscript.sh >/path/log 

I found the script did not run, since the system created an empty log file. Then I add 2>&1 at the end of the above command:

0 10 * * * /bin/bash /path/myscript.sh >/path/log 2>&1

And try to find errors of whatsoever. Strangely, with adding the 2>&1, cron did not even create an empty log file. Nothing.

Any idea on what's going on here when adding the 2>&1?


Solution

  • The default behaviour of cron is to send stderr via email to the user running the cronjob.

    From man cron:

    When executing commands, any output is mailed to the owner of the crontab (or to the user specified in the MAILTO environment variable in the crontab, if such exists).

    To circunvent this behaviour, you can indeed redirect the stderr like you are trying. However, it needs some extra tuning.

    As seen in Redirect stderr with date to log file from Cron, you can use a subshell to redirect stderr to stdin and then redirect everything normally: (cron expression 2>&1) > /your/log/file. In your case:

    0 10 * * * (/bin/bash /path/myscript.sh 2>&1) >/path/log