Using tee to create a log

Kevin Buettner plug-discuss@lists.PLUG.phoenix.az.us
Thu, 26 Jul 2001 14:38:13 -0700


On Jul 26,  1:55pm, Wayne Conrad wrote:

> "&>" is really a shorthand for "2>&1 >".  These two commands do the same thing:
> 
>   foo &> logfile            # bash-specific shorthand for...
>   foo 2>&1 > logfile        # this, which works in both bash and ksh
> 
> I hope this isn't too much (or too confusing).

This is incorrect (but an easy mistake to make).  The command:

    foo &>logfile

is actually equivalent to:

    foo >logfile >&1

The command that you listed, ``foo 2>&1 >logfile'' actually routes
stderr to the current stdout and routes stdout to logfile.  The following
Perl script may be used to illustrate the difference:

--- test-stdout-stderr ---
#!/usr/bin/perl -w

print STDOUT "stdout\n";
print STDERR "stderr\n";
--- end test-stdout-stderr ---

Now lets try some different tests:

    # No redirection
    ocotillo:ptests$ ./test-stdout-stderr 
    stdout
    stderr

    # Redirect stdout to logfile.
    ocotillo:ptests$ ./test-stdout-stderr >logfile
    stderr
    ocotillo:ptests$ cat logfile
    stdout

    # Redirect stderr to logfile.
    ocotillo:ptests$ ./test-stdout-stderr 2>logfile
    stdout
    ocotillo:ptests$ cat logfile
    stderr

    # Redirect stdout to logfile and then redirect stderr to (the now
    #   redirected) stdout.
    ocotillo:ptests$ ./test-stdout-stderr >logfile 2>&1
    ocotillo:ptests$ cat logfile
    stderr
    stdout

    # Redirect stderr to stdout and redirect stdout to logfile.  Note
    #   that this *does not* cause stderr to be redirected to logfile;
    #   a copy of the descriptor is made prior to performing the second
    #   redirection.
    ocotillo:ptests$ ./test-stdout-stderr 2>&1 >logfile
    stderr
    ocotillo:ptests$ cat logfile
    stdout

    # Like the above, but pipe the ``stderr redirected to stdout''
    #    portion to a command which'll save this output to logfile2.
    ocotillo:ptests$ ./test-stdout-stderr 2>&1 >logfile | cat >logfile2
    ocotillo:ptests$ cat logfile
    stdout
    ocotillo:ptests$ cat logfile2
    stderr

If all of this confuses you, just think about how you'd do the
equivalent of the above redirections in C using open() and dup2().  In
fact, to really understand this stuff it would be a valuable exercise
to code the above examples in C...

Kevin