What is and what is "2>&1" for?

Asked

Viewed 14,623 times

17

When we want to direct the output in order to execute a command without receiving any information, among which potential execution errors we use:

meuComando >/dev/null 2>&1

Effectively with >/dev/null we are sending the output to a device file representing an empty (black hole) but what is 2>&1 and what it’s for ?

  • Related: http://answall.com/questions/52622/ (or dup?)

  • 2

    @bfavaretto I had not seen this, but the question itself focuses on a different instruction from this... I think the two questions can coexist!

  • Also related: http://answall.com/questions/40254/comond-messagingpara-stderr-no-bash-via-command echo

2 answers

24


The command > is equivalent to 1>, and means you’re redirected to standard output (standard output - stdout) to the specified file. Already the 2> means that one is redirecting the standard error output (standard error output - stderr). Beyond the 1 and of 2, there is also the 0 representing the standard input (stdin).

In that case, meuComando is redirecting the standard output to /dev/null; error output is also being redirected, but not to one file, but to another stream. According to that answer in Soen, the use of & indicates that the output will go to another file Descriptor, and not to a file. And as seen, the file Descriptor 1 represents the stdout.

Therefore, 2>&1 means "redirect the stderr to the stdout". Like the stdout is already redirecting to the "black hole", this will also be done with the stderr. But even if it wasn’t, this command can be useful if you want to send both outputs to the same destination, not each one to a different file:

meuComando > saida_e_erros.txt 2>&1
  • 1

    Your answer is better than Soen’s, by the way. To contribute, I leave the TLDP link on redirecting I/O (in English): http://tldp.org/LDP/abs/html/io-redirection.html

11

1 means the same as stdout and 2 means the same as stderr, so it’s just a simpler way to redirect everything that is sent to the error output to the standard output. The & is necessary to avoid confusion with a file name. Without it the syntax could be interpreted as 1 being a filename but in this case the syntax refers to a file descriptor.

Then in your example nothing will come out in the default output because you are nullifying it and also the results of the errors. If only the >/dev/null were used, errors would appear.

In conclusion: errors are directed to the standard output with the syntax 2>&1 and then all the standard output, including the one that was redirected to it is redirected again to >/dev/null who will take care to disappear with any message.

Confirmation can be obtained in the responses of this question in the OS.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.