How to stop redirection via exec

I want to redirect some output of a script to a file.

REDIRECT_FILE="foo.txt"

echo to console

# starting redirect
exec > $REDIRECT_FILE

echo to file
echo ...
echo ...

# stop redirect
exec >&-

echo end of script

"end of script" should be written to stdout.
But instead there is a "Bad file descriptor" error message.

exec 1>&- does not work too.

What is the correct term to stop the redirection?

Asked By: Andy A.

||

The exec 1>&- closes stdout. It doesn’t revert it to the original value because you’d already replaced that with exec > $REDIRECT_FILE (which should be exec > "$REDIRECT_FILE" to protect the variable’s value from any further processing by by the shell).

To revert stdout to its original value you need to save it

exec 3>&1                  # Save stdout as FD 3
exec 1>"$REDIRECT_FILE"    # Redirect stdout to a file
…
exec 1>&3                  # Revert stdout to its original value
Answered By: Chris Davies
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.