Bash Exec – Practical Use Cases and Examples

bashexecshell-builtinshell-script

Consider this from the documentation of Bash' builtin exec:

exec replaces the shell without creating a new process

Please provide a use case / practical example. I don’t understand how this makes sense.

I googled and found about I/O redirection. Can you explain it better?

Best Answer

exec is often used in shell scripts which mainly act as wrappers for starting other binaries. For example:

#!/bin/sh

if stuff;
    EXTRA_OPTIONS="-x -y -z"
else
    EXTRA_OPTIONS="-a foo"
fi

exec /usr/local/bin/the.real.binary $EXTRA_OPTIONS "$@"

so that after the wrapper is finished running, the "real" binary takes over and there is no longer any trace of the wrapper script that temporarily occupied the same slot in the process table. The "real" binary is a direct child of whatever launched it instead of a grandchild.

You mention also I/O redirection in your question. That is quite a different use case of exec and has nothing to do with replacing the shell with another process. When exec has no arguments, like so:

exec 3>>/tmp/logfile

then I/O redirections on the command line take effect in the current shell process, but the current shell process keeps running and moves on to the next command in the script.

Related Question