重定向输出和错误到一个文件,拷贝只是标准错误到另一个

重定向输出和错误到一个文件,拷贝只是标准错误到另一个

问题描述:

我要输出和错误输出重定向到一个共同文件:

I want to redirect the output of stdout and stderr to a common file:

./foo.sh >stdout_and_stderr.txt 2>&1

但也只是重定向错误输出到一个单独的文件。我试过的变化:

But also redirect just stderr to a separate file. I tried variations of:

./foo.sh >stdout_and_stderr.txt 2>stderr.txt 2>&1

但他们没有工作在bash,例如完全正确标准错误只被重定向到输出文件中的一个。重要的是,合并后的文件preserves第一code段的网上订购,因此没有倾倒单独的文件,后来的完美组合。

but none of them work quite right in bash, e.g. stderr only gets redirected to one of the output files. It's important that the combined file preserves the line ordering of the first code snippet, so no dumping to separate files and later combining.

有没有很好地解决了这个在bash?

Is there a neat solution to this in bash?

您可以使用一个额外的文件描述符和 T恤

You can use an additional file descriptor and tee:

{ foo.sh 2>&1 1>&3- | tee stderr.txt; } > stdout_and_stderr.txt 3>&1

请注意,行缓冲可能会导致标准输出输出的显示顺序。如果这是一个问题,有办法克服包括使用 无缓冲