2

In linux we can redirect stdout and stderr or both of them to files. For example:

  • Redirect stdout and stderr to two files: command 1>out 2>err. By this way, we can separate output and error in two difference files.
  • Redirect both stdout and stderr to files: command &>all. By this way, we can capture the appearance orders of output and error message.

I want to combine the two above command: command 1>out 2>err &>all, to capture the appearance order of output and error, and separate output and error. But the above command does not work, the out and err files are empty. If I reverse the order, the all file will be empty. So, is there anyway to combine the two command above as I want?

migrated from serverfault.com Jul 12 '16 at 8:34

This question came from our site for system and network administrators.

1

In bash it's a bit tricky:

command 2> >(tee err) 1> >(tee out) | tee >all

Here we need process substitution >(...) and tee to work around the problem. With process substitution the tee process is attachted to the corresponding channel. tee then writes the lines into the file and prints then to the STDOUT. So after writing to the files, both STDERR and STDOUT will be printed to STDOUT. In bash, we cannot use multiple redirections of the same chanel in one command. That's why we need to pipe that output to tee again, which then just prints it.


Within zsh (notice the option MULTIOS must be set, which is detault in zsh):

command >out 2>err &>all
  • you can use one less tee (assuming you didnt want to see the output anyway) with ` 3>all 1> >(tee out >&3) 2> >(tee err >&3)` – meuh Jul 12 '16 at 9:19
  • @meuh Ah, good idea over another file descriptor. – chaos Jul 12 '16 at 9:27
  • 1
    Note that this does not preserve the order of messages to stdout and stderr in the joint output file (all), because the intermediate calls to tee proceed at their own pace. – Gilles Jul 12 '16 at 22:41
  • @meuh Magic code! If you are availabe,could you help to make some specification for it here? – yode Jul 10 '17 at 7:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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