Bash – How to stop redirection in bash

bashio-redirectionshell

I use :

exec >script.log 2>&1

in my script to redirect all output to a file. At the end of the script I would like to print a message to the screen. How do I stop the redirection?

Best Answer

You can call exec again to restore the original descriptors. You'll need to have saved them somewhere.

exec 3>&1 4>&2 1>script.log 2>&1
… logged portion …
exec 1>&3 2>&4
echo >&2 "Done"

Inside the logged portion, you can use the original descriptors for one command by redirecting to the extra descriptors.

echo "30 seconds remaining" >&3

Alternatively, you can put the logged portion of your script inside a compound command and redirect that compound command. This doesn't work if you want to use the original descriptors in a trap somewhere within that redirected part.

{
… logged portion …
} >script.log 2>&1
echo >&2 "Done"
Related Question