Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Linux by (18.4k points)

In the Unix shell, if I want to combine stderr and stdout into the stdout stream for further manipulation, I can append below following at one end of my command:

2>&1

So, if I want to use the head-on output from g++, I can do something like this:

g++ lots_of_errors 2>&1 | head

so I can see only a 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 completely understand the special syntax of the particular trick.

Can someone break that up and explain step by step what 2>&1 means?

1 Answer

0 votes
by (36.8k points)

File descriptor 1 has a standard output (stdout).

File descriptor 2 has a standard error (stderr).

There is one way to remember the construct (although it is not entirely accurate): at first, 2>1 may look like the good way to redirect stderr to stdout. However, it will be interpreted as the "redirect stderr to your file named 1". & indicates that what follows and precedes is the file descriptor and not the filename. So a construct becomes 2>&1.

Consider >& as redirect merger operator.

Come and join Linux training to gain great knowledge. 

Do check out the video below

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 13, 2020 in Linux by blackindya (18.4k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...