Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

In the shell, what does “ 2>&1 ” mean?

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:

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?

3 Answers

According to my knowledge :
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.
2 is the console standard error.

1 is the console standard output.

This is the standard Unix, and Windows also follows the POSIX.

E.g. when you run

perl 2>&1

the standard error is redirected to standard output, so you can see both outputs together:

perl > debug.log 2>&1

After execution, you can see all the output, including errors, in the debug.log.

perl 1>out.log 2>err.log

Then standard output goes to out.log, and standard error to err.log.

I suggest you to try to understand these.
The numbers refer to the file descriptors (fd).

Zero is stdin
One is stdout
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.

Login / Signup to Answer the Question.