You’d like to redirect output for an entire script and you’d rather not have to edit every echo or printf statement.
Use a little known feature of the exec
command to redirect STDOUT
or
STDERR
:
# Optional, save the "old" STDERR exec 3>&2 # Redirect any output to STDERR to an error log file instead exec 2> /path/to/error_log # script with "globally" redirected STDERR goes here # Turn off redirect by reverting STDERR and closing FH3 exec 2>&3-
Usually exec replaces the running shell with the command supplied in its arguments, destroying the original shell. However, if no command is given, it can manipulate redirection in the current shell. You are not limited to redirecting STDOUT or STDERR, but they are the most common targets for redirection in this case.
help exec
18.225.57.126