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?
Here is one way to remember this construct (altough 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 is a file descriptor and not a filename. So the construct becomes: 2>&1.
The numbers refer to the file descriptors (fd). Zero is stdin, one is stdout, and two is stderr. "2>&1" redirects fd 2 to 1. This works for any number of file descriptors if the program uses them.
You can look at /usr/include/unistd.h if you forget them:
/* Standard file descriptors. */#define STDIN_FILENO 0/* Standard input. */#define STDOUT_FILENO 1/* Standard output. */#define STDERR_FILENO 2/* Standard error output. */
That said I have written C tools that use non-standard file descriptors for custom logging so you don't see it unless you redirect it to a file or something.
Redirecting Standard Output and Standard Error This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word.
There are two formats for redirecting standard output and standard error:
&>word and >&word
Of the two forms, the first is preferred. This is semantically equivalent to