tags:

views:

357

answers:

5

Hi

Quick one, 2>&1 redirect stderr to stdout, but what does the ampersand mean. I know if we had 2 > 1 it would output to file named 1, what does the ampersand do ?

Thanks

+2  A: 

2>&1 redirects standard error (file handle 2) to the same file that standard output (file handle 1) is currently going to.

It's a positional thing so:

prog >x 2>&1 >y

will actually send standard error to x and standard output to y (send stdout to x, send stderr to same as current stdout (x), send stdout to y).

paxdiablo
I'd upvote this several times if I could. I've been puzzling this over, and your explanation about the importance of *order* is clearer than the current bash documentation: http://www.gnu.org/software/bash/manual/bashref.html#Redirections. Thanks!
FM
+1  A: 

From info bash:

3.6.7 Duplicating File Descriptors
----------------------------------

The redirection operator
     [N]<&WORD
   is used to duplicate input file descriptors.  If WORD expands to one
or more digits, the file descriptor denoted by N is made to be a copy
of that file descriptor.  If the digits in WORD do not specify a file
descriptor open for input, a redirection error occurs.  If WORD
evaluates to `-', file descriptor N is closed.  If N is not specified,
the standard input (file descriptor 0) is used.

   The operator
     [N]>&WORD
   is used similarly to duplicate output file descriptors.  If N is not
specified, the standard output (file descriptor 1) is used.  If the
digits in WORD do not specify a file descriptor open for output, a
redirection error occurs.  As a special case, if N is omitted, and WORD
does not expand to one or more digits, the standard output and standard
error are redirected as described previously.

So 2>&1 duplicates fd 1 onto fd 2.

Douglas Leeder
+2  A: 

It copies file descriptor 1 to file descriptor 2. FD2 is stderr and FD1 is stdout, so it makes any output to stderr go to stdout instead.

Ignacio Vazquez-Abrams
mikip
It does manipulation of the file descriptors.
Ignacio Vazquez-Abrams
+2  A: 

The ampersand belongs to the "1", so the snippet really has three parts: "2", ">", "&1". They mean, respectively, "take the data from output stream 2 (which is standard error)", "redirect it", and the redirection target, which is output stream 1. So "&" here allows you to redirect to an existing stream, rather than to a file.

sleske
A: 

The ampersand doesn't do anything - it's the character in the 2>&1 operator rather than being a thing in its own right.

bash supports several redirection operators, the 2>&1 operator or the &> operator tie together the streams of the process before or after redirection.

Pete Kirkham