0

I know how to direct the entire output of a cron job into a file, but I'm having trouble running a shell script that has multiple redirects within the file. So, my crontab entry is:

0 * * * * /bin/sh /path/to/script

Then, inside of /path/to/script, it calls two long-running commands and backgrounds them:

/path/to/command1 2>&1 >/path/to/output1 &
/path/to/command2 2>&1 >/path/to/output2 &

When I run /path/to/script from a bash shell, everything works correctly. When I run it via a cron job, output1 and output2 are created, but are blank, and the output is instead sent via cron email. I've tried "nohup command1", no luck either. How do I get the output to redirect to the files like I expect? Thanks!

joshwoodward
  • 201
  • 2
  • 10
  • 2
    Are you getting stderr of the commands in the cron email? Undoubtedly, you meant `command1 > output1 2>&1 &`. Order matters. – William Pursell May 28 '17 at 13:58
  • I'm getting the standard output in the cron email, I haven't checked the stderr. But the result is the same if I leave 2>&1 out of the script. – joshwoodward May 28 '17 at 14:02
  • Make sure that you are adding the complete path you your output files. – Raman Sailopal May 28 '17 at 14:03
  • @RamanSailopal That's a good point that I should have clarified. "output1" and "output2" are the full paths to the output. The files are created, they're just empty when running from cron. – joshwoodward May 28 '17 at 14:05
  • To mirror what William said, since it seems that it didn't sink in the first time: `> file 2>&1` redirects both stderr and stdout to `file`. `2>&1 >file` only redirects stdout to the file, and redirects stderr to wherever stdout was *originally* (pre-redirection!) going to go. – Charles Duffy May 28 '17 at 14:44
  • So, you **don't** want to **leave `2>&1` out**; instead, you want to *put it after* the redirection to the file. This is covered in [BashFAQ #55](http://mywiki.wooledge.org/BashFAQ/055). – Charles Duffy May 28 '17 at 14:45
  • BTW, if you really want your shell to be `bash` -- as the question is tagged -- use `bash scriptname` and a `#!/bin/bash` shebang; `sh` is only guaranteed to be a POSIX sh implementation, not to be any *specific* POSIX sh implementation; and even when it *is* bash, it runs in compatibility mode when called by that name. – Charles Duffy May 28 '17 at 14:48

0 Answers0