How to redirect output of an entire shell script within the script itself?

Is it possible to redirect all of the output of a Bourne shell script to somewhere, but with shell commands inside the script itself?

Redirecting the output of a single command is easy, but I want something more like this:

#!/bin/sh
if [ ! -t 0 ]; then
    # redirect all of my output to a file here
fi

# rest of script...

Meaning: if the script is run non-interactively (for example, cron), save off the output of everything to a file. If run interactively from a shell, let the output go to stdout as usual.

I want to do this for a script normally run by the FreeBSD periodic utility. It’s part of the daily run, which I don’t normally care to see every day in email, so I don’t have it sent. However, if something inside this one particular script fails, that’s important to me and I’d like to be able to capture and email the output of this one part of the daily jobs.

Update: Joshua’s answer is spot-on, but I also wanted to save and restore stdout and stderr around the entire script, which is done like this:

# save stdout and stderr to file 
# descriptors 3 and 4, 
# then redirect them to "foo"
exec 3>&1 4>&2 >foo 2>&1

# ...

# restore stdout and stderr
exec 1>&3 2>&4

5 Answers
5

Leave a Comment