Search code examples
bashshellunix

What does " 2>&1 " mean?


To combine stderr and stdout into the stdout stream, we append this to a command:

2>&1

For example, the following command shows the first few errors from compiling main.cpp:

g++ main.cpp 2>&1 | head

But what does 2>&1 mean?


Solution

  • File descriptor 1 is the standard output (stdout).
    File descriptor 2 is the standard error (stderr).

    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. Thus, we use 2>&1. Consider >& to be a redirect merger operator.