understanding bash "exec 1>&2" command understanding bash "exec 1>&2" command bash bash

understanding bash "exec 1>&2" command


exec is a built-in Bash function, so it can have special behavior that an external program couldn't have. In particular, it has the special behavior that:

If COMMAND is not specified, any redirections take effect in the current shell.

(That's quoting from the message given by help exec.)

This applies to any sort of redirection; you can also write, for example, any of these:

exec >tmp.txtexec >>stdout.log 2>>stderr.logexec 2>&1

(It does not, however, apply to pipes.)


The why is an accident of history, there isn't a great reason for it.

The redirection operators are applied to any program (for example, cat) and the >& form was added to express the "duplicate file descriptor 1 from 2" because it was useful. The >& syntax probably was used because they were running out of special characters and >& was nonsense given the basic meaning of & and > (but don't quote me on that). This stuff all dates back to the early Bourne shell around 1977.

Why exec plus a redirection to alter the input and output of the current shell? Probably because there was already a meaning for the null command > path which had the same effect as cat /dev/null > path but was easier to type, and when your teletype ran at 10 characters per second at best, that mattered. So the exec built-in was then overloaded: with no arguments, it applied the redirection operations to itself.

Since bash tries to adhere to Bourne shell convention as much as possible, you get these antiquities which, as you suspect, you just have to remember especially if you are trying to impress other members of the appropriate sex (i.e. "chicks dig a guy who knows his i/o redirection arcana").


Original source: http://tldp.org/LDP/abs/html/x17784.html

An exec <filename command redirects stdin to a file. From that point on, all stdin comes from that file, rather than its normal source (usually keyboard input). This provides a method of reading a file line by line and possibly parsing each line of input using sed and/or awk.

Similarly, an exec >filename command redirects stdout to a designated file. This sends all command output that would normally go to stdout to that file.

Note that exec N > filename affects the entire script or current shell. Redirection in the PID of the script or shell from that point on has changed. However, N > filename affects only the newly-forked process, not the entire script or shell.

Further reading that will interest you can be found @ http://tldp.org/LDP/abs/html/io-redirection.html. There are lots of neat little redirection tricks you can do.