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

7

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

meuComando >/dev/null 2>&1

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

asked by anonymous 25.03.2015 / 19:55

2 answers

14

The > command is equivalent to 1> , which means that the standard output ( standard output - stdout ) is redirected to the indicated file. The 2> means that the standard error output ( standard error output - stderr ) is being redirected. In addition to 1 and 2 , there is also the 0 that represents the default entry ( stdin ).

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

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

meuComando > saida_e_erros.txt 2>&1
    
25.03.2015 / 20:06
8

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. & is required 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.

So in your example, nothing will come out of the standard output because you are overriding it and also the results of the errors. If only >/dev/null was used, errors would appear.

In conclusion: errors are directed to standard output with the 2>&1 syntax and then all standard output, including what was redirected to it, is redirected back to >/dev/null , which will take care of disappearing with any message

Verification can be obtained from responses from this question in the SO .

    
25.03.2015 / 20:07