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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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"
Method 2
Use additinal fd 3 and 4 for stdout and stderr and simply redirect 1 and 2 to them at the end of your script:
exec 3>&1 4>&2 exec >script.log 2>&1 echo "Some code" exec >&3 2>&4 echo "Done"
Method 3
First you should check whether or not you have a tty at all.
if tty -s; then
echo "Hello, World" > $(tty)
fi
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0