In Bourne-like shells (sh, bash, ksh), exec serves two functions:
It can replace your current program with another, or can help you control input and output more easily.
The first use is often used at the last line of a .profile:
Without the "exec", someprog would still run, but when the user quit, they'd be returned to .profile which, having nothing else to do, would drop them to a shell prompt. With the "exec", leaving the program brings them to login.
For redirecting input, exec is very handy. The following little script happily echoes whatever you type, unless you type Q:
date > tt exec 5<&0 while true do read stuff echo $stuff exec <&5 case $stuff in [qQ]) exec < tt;; esac done
This illustrates how you can move back and forth between different input sources. The "exec 5<&0" saves the current standard input so that we can later restore it (exec <&5). If the input sees Q, then the file tt is read instead.
If you do
exec > tt ls
the output of "ls" will be in tt (do "exec > /dev/tty" to return things to normal).
You can specifically close a file descriptor too:
Got something to add? Send me email.
Increase ad revenue 50-250% with Ezoic