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?
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?
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"
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"
exec 3>/dev/stdout 4>/dev/stderr -bash: /dev/stdout: Permission denied
– Willem
Jun 28 '13 at 09:24
First you should check whether or not you have a tty at all.
if tty -s; then
echo "Hello, World" > $(tty)
fi
tty
utility. You can redirect to the special device /dev/tty
.
– Dennis Williamson
Jun 28 '13 at 13:04
>&3
makes this my preferred solution. Thanks (again)! – Willem Jul 03 '13 at 20:16