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?
2 is a standard error (stderr) file descriptor. > is used for redirection. & indicates follow a file descriptor, not a file name. 1 is a standard output (stdout) file descriptor.
1 "Standard output" output file descriptor. The expression 2>&1 copies file descriptor 1 to location 2 , so any output written to 2 ("standard error") in the execution environment goes to the same file originally described by 1 ("standard output").
and >&2 means send the output to STDERR, So it will print the message as an error on the console. You can understand more about shell redirecting from those references: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Redirections.
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.
File descriptor 1 is the standard output (stdout
).
File descriptor 2 is the standard error (stderr
).
Here is one way to remember this construct (although it is not entirely accurate): at first, 2>1
may look like a good way to redirect stderr
to stdout
. However, it will actually be interpreted as "redirect stderr
to a file named 1
". &
indicates that what follows and precedes is a file descriptor and not a filename. So the construct becomes: 2>&1
.
Consider >&
as redirect merger operator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With