exec command replaces the current shell process with the specified command. Normally, when you run a command a new process is spawned (forked). The
exec command does not spawn a new process. Instead, the current process is overlaid with the new command. In other words the
exec command is executed in place of the current shell without creating a new process.
There are three most common uses of exec command:
1. Replacement of process
If you open a new
bash shell as
pstree it looks like
bash shell is still there and you got a new
bash shell. Whereas if you open a new bash shell as,
$ exec bash
Here the old
bash is replaced with new one. It is particularly useful to exit from multiple login in one command. It is more secure and eradicates the chance of leaving an open terminal by mistake. See Exit from both root and user with one command
Example-2: you can open a file as
$ exec vi filename.txt
When you quit
vi there is no need to close the terminal separately as the shell is already replaced. As soon as you close the vi the terminal is also closed.
2. A method of redirection of file descriptors within the shell scripts
exec command can also be used in shell scripts dynamically open, close, and copy file descriptors. That permits performing redirection of STDIN, STDERR, STDOUT and other file descriptors to various files inside the shell script, instead of command invocation string. If you do not specify a command or arguments, you can specify redirection symbols and file descriptors to perform these functions.
Say you have a shell script
script.sh you want to have a log file
script.log, you can use
which is equivalent to
./script &>> /path/to/script.log
./script >> /path/to/script.log 2>&1
3. Creating stages of the process using exec command
You can also use the exec command to create a set of shell scripts that execute one another sequentially like stages of the process. Instead of spawning new processes each time you need to transfer the control to the next script you execute the exec command .
In this case the last statement of each stage should be
exec command that invokes the next stage.
See the uses of the
exec command in shell scripts for more.
Note: Part of above is taken from this.