I want to write stdout to a file but also prints stdout and stderr. I tried using tee:

prog | tee stdout.txt

but this causes the printed stderr and stdout to be interleaved incorrectly, i.e. if the correct output should be

OUT1 ERR1
OUT2 ERR2
OUT3 ERR3
OUT4 ERR4

using tee might print them out of order, e.g.:

ERR1 ERR2
OUT1
OUT2 
OUT3 ERR3 
OUT4
ERR4

Is there any way to print both stdout and stderr to screen and also write the stdout to a file without gobbling up the printed output?

link|improve this question

71% accept rate
1  
See Show only stderr on screen but write both stdout and stderr to file. There's no way unless you're willing to do some programming. – Gilles May 19 '11 at 6:50
feedback

2 Answers

I would forward stdout to a file, then use tail to see the file content as it is written. That means you need to have two terminals open.

Terminal one:

prog > stdout.txt

Terminal two:

tail -f stdout.txt

So, in terminal two you will see stdout content as it is written to stdout.txt, and in terminal one you will see stderr. You can also forward both stdout and stderr to a file, and do the same thing. In that case you need to use prog >& outerr.txt. (This will work on tcsh, but you can do it in bash, too.)

link|improve this answer
feedback

Try process substitution.

The following program:

#! /bin/bash

prog () {
    for n in 1 2 3 4 ; do
    echo OUT$n
    echo ERR$n >&2
    done
}

prog
echo
prog | tee stdout.txt
echo
prog >(tee stdout.txt >&2)

Will generate the following output:

OUT1
ERR1
OUT2
ERR2
OUT3
ERR3
OUT4
ERR4

ERR1
ERR2
ERR3
ERR4
OUT1
OUT2
OUT3
OUT4

OUT1
ERR1
OUT2
ERR2
OUT3
ERR3
OUT4
ERR4
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.