What will this command do?
exec 2>&1
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
.
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.
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!