directing output in crontab

Chris plug.org at 2nerds.com
Tue Jul 22 16:29:37 MDT 2008


On Tue, Jul 22, 2008 at 4:06 PM, Wade Preston Shearer
<lists at wadeshearer.com> wrote:
>> For /bin/sh, the typical syntax to send stderr to the same place as
>> stdout is "2>&1".
>
> Wouldn't that take the standard error and redirect it back to the display?

cron job output is typically emailed to the invoking user, not sent to
the display, so to be precise we need not to refer to "the display"
when talking about output from jobs invoked from a crontab.  Keeping
that in mind, the answer to your question is: it depends on the order
in which you write the redirection operators. (This is true both for
cron jobs as well as commands typed interactively to the /bin/sh
shell.  The only difference is where "stdout" goes by default: to the
display for interactive shells, piped to an email program for cron
jobs.)

Anyway:

If you write "2>&1 >myfile", then stderr is NOT sent to myfile; stderr
goes to stdout's original descriptor.

If you write ">myfile 2>&1", then stderr goes to myfile along with
stdout. (This is what you want, I think.)

The 2>&1 operator redirects stderr to whereever stdout is pointing at
that moment when 2>&1 is parsed.  So if you redirect stdout _after_
writing 2>&1, then stderr goes to stdout's original descriptor
(because stdout hasn't been redirected yet).  If you redirect stdout
_before_ writing 2>&1, then stderr goes to stdout's new descriptor.

> I want to take the standard output and standard error and send them both to a
> log file.

To do that, on the command line, redirect stdout first, then write 2>&1.
(e.g. mycommand >my_combined_output_file 2>&1)

Chris



More information about the PLUG mailing list