Redirecting Output for the Life of a Script

Problem

You’d like to redirect output for an entire script and you’d rather not have to edit every echo or printf statement.

Solution

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-

Discussion

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.

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.