Redirect STDOUT & STDERR to file and then on screen

Dear all,
redirecting STDOUT & STDERR to file is quite simple, I'm currently using:

exec 1>>/tmp/tmp.log; exec 2>>/tmp/tmp.log

But during script execution I would like the output come back again to screen, how to do that?

Thanks
Lucas

This isn't simple, and can change the order of your output, because it means making one stream print into two separate places. To do that, you need to use tee or something like tee and connect to them with fifos.

mkfifo /tmp/$$-err /tmp/$$-out

( exec tee -a stdout.log </tmp/$$-out ) &
( exec tee -a stderr.log </tmp/$$-err >&2 ) &

exec 1>/tmp/$$-out
exec 2>/tmp/$$-err
rm -f /tmp/$$-out /tmp/$$-err


echo "This into stdout.log"
echo "This into stderr.log" >&2

This can change the order of your output because the path is no longer direct. stderr was guaranteed to be unbuffered, before, but now must pass through several buffers on its way to the terminal.

1 Like

Thanks, I'll try it, but from your code, I still don't understand how activate screen log OR file log! :rolleyes:

Because I don't need both at the same time, and the flow is something like:

Start Application >> Log files
execute some commands >> Log files
execute other commands >> Log files
if $1 = "--debug" then disable Log files and show the output on screen
      execute some commands > Screen Log
else
      execute other commands >> Log files
exit

Oh, you just want to save them for later? That's much easier!

# Save backups of FD's
exec 5>&1
exec 6>&2

...

# Redirect into files
exec 1>stdout.log
exec 2>stderr.log

...

# Restore to terminal
exec 1>&5
exec 2>&6
1 Like

Thanks a million, it works perfect! :b: