Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 264
Tristan Havelick Avatar asked May 03 '09 22:05

Tristan Havelick


People also ask

What does 2 mean in shell?

2 is a standard error (stderr) file descriptor. > is used for redirection. & indicates follow a file descriptor, not a file name. 1 is a standard output (stdout) file descriptor.

What does 2 &1 mean in shell script?

1 "Standard output" output file descriptor. The expression 2>&1 copies file descriptor 1 to location 2 , so any output written to 2 ("standard error") in the execution environment goes to the same file originally described by 1 ("standard output").

What is >& 2 in shell script?

and >&2 means send the output to STDERR, So it will print the message as an error on the console. You can understand more about shell redirecting from those references: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Redirections.

What does 2 >& 1 at the end of a command do?

The 1 denotes standard output (stdout). The 2 denotes standard error (stderr). So 2>&1 says to send standard error to where ever standard output is being redirected as well.


1 Answers

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.

like image 183
Ayman Hourieh Avatar answered Sep 20 '22 16:09

Ayman Hourieh