Capture all output, error, warning and their appearance order of linux’s command

command lineio-redirection

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?

Best Answer

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
Related Question