为了能够在事后调试测试,我还需要在输出的序列中看到stdout和stderr.所以我必须将它们保存到同一个文件/变量/中,或者同时将它们发送到终端,以便单独保存它们.
出于效率和准确性的原因,我当然不能每次测试两次.
例如,可以将stdout重定向到stdout.log,将stderr重定向到stderr.log,并将它们两个重定向到output.log中的同一命令吗?或者为stdout和stderr单独使用同步tee命令?或者将stdout和stderr的副本保存为单独的变量?
更新:看起来tim的解决方案几乎可以工作(修改为在终端上输出而不是记录到all.log):
$set -o pipefail ${ { echo foo | tee stdout.log 2>&3 3>&- } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&- } 3>&2 4>&1 foo $cat stdout.log foo $cat stderr.log ${ { echo foo >&2 | tee stdout.log 2>&3 3>&- } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&- } 3>&2 4>&1 foo $cat stdout.log $cat stderr.log foo $bar=$({ { echo foo | tee stdout.log 2>&3 3>&- } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&- } 3>&2 4>&1) $echo "$bar" foo $cat stdout.log foo $cat stderr.log $bar=$({ { echo foo >&2 | tee stdout.log 2>&3 3>&- } 2>&1 >&4 4>&- | tee stderr.log 2>&3 3>&- } 3>&2 4>&1) $cat stdout.log $cat stderr.log foo $echo "$bar" foo
除了最后一次迭代之外,这似乎有效,其中bar的值设置为stderr的内容.有关所有这些工作的建议吗?
从那个页面:
But some people won’t accept either the loss of separation between stdout and stderr,or the desynchronization of lines. They are purists,and so they ask for the most difficult form of all — I want to log stdout and stderr together into a single file,BUT I also want them to maintain their original,separate destinations.
In order to do this,we first have to make a few notes:
- If there are going to be two separate stdout and stderr streams,then some process has to write each of them.
- There is no way to write a process in shell script that reads from two separate FDs whenever one of them has input available,because the shell has no poll(2) or select(2) interface.
- Therefore,we’ll need two separate writer processes.
- The only way to keep output from two separate writers from destroying each other is to make sure they both open their output in append mode. A FD that is opened in append mode has the guaranteed property that every time data is written to it,it will jump to the end first.
So:
# Bash > mylog exec > >(tee -a mylog) 2> >(tee -a mylog >&2) echo A >&2 cat file echo B >&2
This ensures that the log file is correct. It does not guarantee that the writers finish before the next shell prompt:
~$./foo A hi mom B ~$cat mylog A hi mom B ~$./foo A hi mom ~$B
另请参见BashFAQ/002和BashFAQ/047.