Redirecting program output

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)

Upvotes: 1

Views: 81

Answers (2)

John Zwinck
John Zwinck

Reputation: 249572

(./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.

Upvotes: 3

user14717
user14717

Reputation: 5171

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

Or do you think the cat file3 is cheating?

Upvotes: 0

Related Questions