In a Unix shell, if I want to combine stderr
and stdout
into the stdout
stream for further manipulation, I can append the following on the end of my command:
2>&1
So, if I want to use head
on the output from g++
, I can do something like this:
g++ lots_of_errors 2>&1 | head
so I can see only the first few errors.
I always have trouble remembering this, and I constantly have to go look it up, and it is mainly because I don't fully understand the syntax of this particular trick.
Can someone break this up and explain character by character what 2>&1
means?
That construct sends the standard error stream (
stderr
) to the current location of standard output (stdout
) - this currency issue appears to have been neglected by the other answers.You can redirect any output handle to another by using this method but it's most often used to channel
stdout
andstderr
streams into a single stream for processing.Some examples are:
Note that that last one will not direct
stderr
tooutfile2
- it redirects it to whatstdout
was when the argument was encountered (outfile1
) and then redirectsstdout
tooutfile2
.This allows some pretty sophisticated trickery.
Provided that
/foo
does not exist on your system and/tmp
does…will print the contents of
/tmp
and print an error message for/foo
will send the contents of
/tmp
to/dev/null
and print an error message for/foo
will do exactly the same (note the 1)
will print the contents of
/tmp
and send the error message to/dev/null
will send both the listing as well as the error message to
/dev/null
is shorthand
Ref:
Type
/^REDIRECT
to locate to theredirection
section, and learn more...An online version is here: 3.6 Redirections
PS:
Lots of the time,
man
was the powerful tool to learn Linux.