tags:

views:

1251

answers:

3

What will this command do?

exec 2>&1
+4  A: 

It ties standard error to standard out

the 2 is stderr and 1 is stdout. When you run a program, you'll get the normal output in stdout, but any errors or warnings usually go to stderr. If you want to pipe all output to a file for example, it's useful to first combine stderr with stdout with 2>&1.

Charles Ma
calling exec without command is not necessarily a hidden feature (its in the bas doc) but new to me nontheless. Funny thing..
Don Johe
It does not 'pipe stderr to stdout'. You could say it 'ties stderr to stdout' or it 'associates stderr and stdout'. Data gets piped, file descriptors do not.
William Pursell
Thanks William, I've changed it to 'ties'
Charles Ma
A: 

Like @cma said, it puts stderr on stdout. The reason you might want this behavior is to use grep or any other utility to capture output that only appears on stderr. Or you might just want to save all the output, including stderr, to a file for later processing.

Mark Rushakoff
+7  A: 

Technically speaking it duplicates, or copies, stderr onto stdout.

Usually you don't need the exec to perform this. A more typical use of exec with file descriptors is to indicate that you want to assign a file to an unused file descriptor, e.g.

exec 35< my_input

BTW Don't forget that the sequence of declaration when piping to a file is important, so

ls > mydirlist 2>&1

will work because it directs both stdout and stderr to the file mydirlist, whereas the command

ls 2>&1 > mydirlist

directs only stdout, and not stderr, to file mydirlist, because stderr was made a copy of stdout before stdout was redirected to mydirlist.

Edit: It's the way that the shell works scanning from left to right. So read the second one as saying "copy stderr onto stdout" before it says "send stdout to mydirlist". Then read the first one as saying "send stdout to the file mydirlist" before it says "duplicate stderr onto that stdout I've set up". I know. It's totally not intuitive!

Rob Wells
Sorry, I do not understand this. So directing stderr to stdout and then directing stdout to a file does not work, but directing stdout to a file and then directing stderr to stdout works? Seems like it should be opposite.
bjarkef
@bjarkef, see edit above.
Rob Wells
Very counter intuitive indeed. I have been trying to do exactly that for I do not know how many times and have wondered why it never works. Thanks a bunch.
bjarkef