sh command: exec 2>&1

valodzka picture valodzka · Aug 1, 2009 · Viewed 45.3k times · Source

What will this command do?

exec 2>&1 

Answer

Rob Wells picture Rob Wells · Aug 1, 2009

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!