In a Unix shell, if I want to combine
stdout into the
stdout stream for further manipulation, I can append the following on the end of my command:
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
File descriptor 1 is the standard output (
File descriptor 2 is the standard error (
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
stdout. However, it will actually be interpreted as "redirect
stderr to a file named
& indicates that what follows is a file descriptor and not a filename. So the construct becomes:
echo test > afile.txt
redirects stdout to
afile.txt. This is the same as doing
echo test 1> afile.txt
To redirect stderr, you do:
echo test 2> afile.txt
>& is the syntax to redirect a stream to another file descriptor - 0 is stdin, 1 is stdout, and 2 is stderr.
You can redirect stdout to stderr by doing:
echo test 1>&2 # or echo test >&2
Or vice versa:
echo test 2>&1
So, in short...
2> redirects stderr to an (unspecified) file, appending
&1 redirects stderr to stdout.