bash – 同步保存stdout,stderr和stdout stderr

前端之家收集整理的这篇文章主要介绍了bash – 同步保存stdout,stderr和stdout stderr前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
出于测试目的,我想分别保存stdout和stderr以供后续代码检查.例如,错误输入的测试运行应该导致输出到stderr,但是stdout没有输出,而具有正确输入的测试运行应该导致输出到stdout,但是没有输出到stderr.保存必须是同步的,以避免测试的竞争条件(所以我不能使用 process substitution).

为了能够在事后调试测试,我还需要在输出的序列中看到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的内容.有关所有这些工作的建议吗?

请看 BashFAQ/106.吃蛋糕也不容易吃.

从那个页面

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/002BashFAQ/047.

原文链接:/bash/387008.html

猜你在找的Bash相关文章