10

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?

Willem
  • 133

3 Answers3

16

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"
6

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"
rush
  • 27,403
  • This returns an error : exec 3>/dev/stdout 4>/dev/stderr -bash: /dev/stdout: Permission denied – Willem Jun 28 '13 at 09:24
  • This error may occur when you're trying to launch your script within another user. Do you use your script via sudo? – rush Jun 28 '13 at 09:51
  • Yes, that's it: I did a su to another account and ran the code. The script I'm writing will be run via sudo, so I'll run into the same problem there. Is there an alternative? – Willem Jun 28 '13 at 10:52
  • I believe there is some elegant solution, unfortunately I know the only option, that may be absolutely unacceptable from security point of view: add your target user to your initial user primary group and add group write permissions for /proc/self/fd/1 before script launch. ( or even more vulnerable - just make temporary write permission for all and remove it right after the script is finished without group changes ). – rush Jun 28 '13 at 15:12
  • 1
    @Willem This is easily fixed by using file descriptors instead of reopening the files, see my edit. – Gilles 'SO- stop being evil' Jun 29 '13 at 00:20
  • @Gilles: works perfect, thanks! (need to remind myself to read up on file descriptors :-) – Willem Jul 03 '13 at 19:56
1

First you should check whether or not you have a tty at all.

if tty -s; then
    echo "Hello, World" > $(tty)
fi