2

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?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Luke
  • 720
  • 1
  • 9
  • 22
  • Probably [this idea](http://stackoverflow.com/a/7145706/1983854) can make it: `0 10 * * * (/bin/bash /path/myscript.sh 2>&1) >/path/log`. Can you check if it does? – fedorqui Mar 11 '15 at 16:49
  • 1
    @fedorqui Yes, it works. Thank you so much. Would be please write it as an answer so that I can take it? – Luke Mar 11 '15 at 17:00

1 Answers1

3

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
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    Correct. I believe this is because cron kind-of does an additional "2>mailfile" at the end to grab errors and mail them, which in the poster's case will redirect stderr to mailfile, and in your case can't as stderr is now 'empty' (the subshell sent all errors to stdout, leaving no stderr at cron's level to be grabbed) – Olivier Dulac Mar 11 '15 at 17:45