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


echo to console

# starting redirect

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?

1 Answer 1


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
  • Thanks! - Should I close "&3" after revert stdout? (add exec 3>&- at the end of the script)
    – Andy A.
    Commented Nov 20, 2023 at 14:09
  • No need - the descriptions will all be cleaned up when the process exits Commented Nov 20, 2023 at 14:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .