1

How do I redirect my program, so that the output goes to 3 file such that

  1. stdout goes to file1
  2. stderr goes to file2
  3. the combined result of stdout and stderr goes to file3 in their original order
  4. While redirecting, the output is also printed to the screen as the program is running

I tried

myprogram > file1 2> file2

but this does not satisfy 3 & 4.

Edit: It would be better if the screen displays messages immediately after they are printed. (to increase responsiveness)

Fermat's Little Student
  • 5,549
  • 7
  • 49
  • 70
  • possible duplicate of [How do I write stderr to a file while using "tee" with a pipe?](http://stackoverflow.com/questions/692000/how-do-i-write-stderr-to-a-file-while-using-tee-with-a-pipe) – Phil Ross Jan 12 '15 at 00:23

2 Answers2

3
(./foo.sh > >(tee out.log) 2> >(tee err.log >&2)) |& tee all.log

What have we done here? First, we create two subshells to run tee out.log and tee err.log, and redirect the appropriate descriptors to them. We are careful to redirect stdout from err.log back to stderr where it belongs, otherwise it will mess up out.log (credit to https://stackoverflow.com/a/692407/4323 for this idea). Second, we put that entire thing in a subshell so that we can redirect its stdout and stderr in one shot to all.log, again using tee to print to the screen at the same time.

One caveat is that the program we're running is likely to buffer stdout when it is not a TTY/PTY (terminal device). If you need immediate output from stdout on your screen and in the files, you can try running your program with unbuffer, a utility which avoids this buffering.

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

myprogram > file1 2> file2 &> file3; cat file3

Or do you think the cat file3 is cheating?

user14717
  • 4,757
  • 2
  • 44
  • 68