up vote 11 down vote favorite
3
share [g+] share [fb]

I know that the > sign is used for output redirection in the command line, but I'm having trouble finding something that explains the use of 2>&1 in the command line. For example:

curl http://www.google.com > /dev/null 2>&1 &
link|improve this question
feedback

2 Answers

up vote 25 down vote accepted

The 1 denotes standard output (stdout). The 2 denotes standard error (stderr).

So 2>&1 says to send standard error to where ever standard output is being redirected as well. Which since it's being sent to /dev/null is akin to ignoring any output at all.

link|improve this answer
Is there a reason that an ampersand appears before the 1, but not before the 2? I thought the & was a reserved character for running a job in the background, but I guess that's only if the ampersand appears as a long character at the end of a command...? – Matt Huggins Nov 16 '09 at 23:24
3  
Because 0 (stdin), 1 (stdout) and 2 (stderr) are actually file descriptors the shell requires an ampersand put in front of them for redirection. It duplicates the file descriptor in this case effectively merging the two streams of information together. – Chealion Nov 16 '09 at 23:36
Thanks for the extra info! – Matt Huggins Nov 16 '09 at 23:38
1  
Think of it this way: if you just had "1" with no ampersand, the shell would create a file named "1" and redirect stderr output to it. – CarlF Nov 17 '09 at 6:05
1  
@Matt Huggins: Yes. That would send all output from stderr straight to /dev/null instead. You can see it in practice by trying curl, curl 1>/dev/null and curl 2>/dev/null just to see the output change. Again the ampersand is only needed for the file descriptor being redirected to. – Chealion Nov 18 '09 at 0:34
show 1 more comment
feedback

2 refers to STDERR. 2>&1 will send STDERR to the same location as 1 (STDOUT).

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.