Execute Command
Understanding the 'exec' Shell Builtin
The exec command is a powerful shell builtin that
allows you to replace the current shell process with a new one. This
means the shell script or interactive session that invoked
exec will terminate, and the new command will take its
place. It's particularly useful for managing process lifecycles and
for redirecting input/output streams without creating a subshell.
Redirecting Standard Output (STDOUT)
You can use exec to redirect all standard output from
within a script to a specified file. This is a common practice for
logging purposes. For example, to send all STDOUT to
foo.log:
# Redirect all STDOUT from within a script to the given file.
exec > foo.log
Redirecting Both STDOUT and Standard Error (STDERR)
Often, you'll want to capture both standard output and standard
error to a single log file. The following command achieves this by
redirecting STDOUT to foo.log and then redirecting
STDERR (file descriptor 2) to the same location as STDOUT (file
descriptor 1):
# Redirect all of both STDOUT & STDERR from within a script to the given file.
exec > foo.log 2>&1
# Or, if on bash(1), this syntax is also viable:
exec &> foo.log
Copying Output While Allowing Normal Operation
In some scenarios, you might want to log output to a file while
still allowing it to be displayed on the terminal. This can be
achieved using process substitution with the
tee command. The following examples demonstrate how to
tee both STDOUT and STDERR to a log file while preserving their
original destinations:
# Copy output to a log file, allowing the outputs to still work as usual.
exec > >(tee -ia foo.log)
exec 2> >(tee -ia foo.log >&2)
These commands use tee -ia foo.log to append
(-a) the output to foo.log and also send
it to the next file descriptor (> for STDOUT,
>&2 for STDERR), effectively duplicating the output.
Further Reading on Shell Redirection
For a deeper understanding of shell redirection and process substitution, consult the following resources: