Shell : quick newb question - redirecting to file

Colin Watson cjwatson at ubuntu.com
Tue Jul 12 11:34:15 UTC 2005


On Tue, Jul 12, 2005 at 07:13:26AM -0400, Stephen R Laniel wrote:
> So you need some way to dump stderr and stdout at the same
> time. Here's how you do it:
> 
> programName 2>&1 >outputFile
> 
> This says "Take filehandle 2 and send it to the same place
> where you send filehandle 1." Then the second '>' says "Now
> take filehandle 1 and send it to outputFile." Voila: both
> stderr and stdout are going to outputFile.

Actually, that's not quite right. 2>&1 >outputFile does the following:

  * turn file descriptor 2 into a duplicate of whatever file descriptor
    1 currently is

  * open file descriptor 1 onto outputFile (closing whatever was
    previously on file descriptor 1)

They happen in that order, so fd 2 gets duplicated from fd 1 *before* fd
1 is redirected to outputFile. The upshot is that stdout will end up in
the file but stderr will go to your terminal.

If you want to redirect both stdout and stderr to a file, use this
instead:

  programName >outputFile 2>&1

This opens fd 1 onto outputFile, and then duplicates that file
descriptor onto fd 2.

Cheers,

-- 
Colin Watson                                       [cjwatson at ubuntu.com]




More information about the ubuntu-users mailing list