在shell中,我如何获得标准输出&;按输出顺序组合的stderr和单独的stderr?

在shell中,我如何获得标准输出&;按输出顺序组合的stderr和单独的stderr?,shell,logging,stdout,stderr,Shell,Logging,Stdout,Stderr,出于构建日志的原因,我想要一个shell脚本 组合命令的stderr和stdout,但也仅单独保存stderr,以便在开始时突出显示stderr。但是,如果需要的话,也可以将它们结合起来进行进一步的分析,包括stdout消息 尝试了很多关于tee和文件描述符的方法,但我不明白这一点 工作的东西 我已经发现,对于zsh,这应该可以工作cmd&>all.txt和2>out.txt,但不幸的是,在sh上不能工作 有一次,我还设法将它们放在一个文件中,但是,这不符合顺序,我得到了所有错误,然后是标准输出

出于构建日志的原因,我想要一个shell脚本 组合命令的stderr和stdout,但也仅单独保存stderr,以便在开始时突出显示stderr。但是,如果需要的话,也可以将它们结合起来进行进一步的分析,包括stdout消息

尝试了很多关于tee和文件描述符的方法,但我不明白这一点 工作的东西

我已经发现,对于zsh,这应该可以工作
cmd&>all.txt和2>out.txt
,但不幸的是,在sh上不能工作

有一次,我还设法将它们放在一个文件中,但是,这不符合顺序,我得到了所有错误,然后是标准输出或其他方式

如果你尝试某事,它应该是sh

这是我的测试脚本:

>&2 echo "error0"
echo "out0"
>&2 echo "error1"
echo "out1"
>&2 echo "error2"
echo "out2"
产出应为:

error0
out0
error1
out1
error2
out2 
以及:

使用
test.sh

#!/bin/sh
for i in `seq 10`; do
  echo "error$i" >&2
  echo "out$i"
done
我得到的结果如下:

$ cat log
out1
out2
error1
out3
error2
error3
out4
error4
out5
error5
out6
error6
out7
error7
out8
error8
out9
error9
out10
error10
$ cat errlog
error1
error2
error3
error4
error5
error6
error7
error8
error9
error10
有时更好,有时更糟

使用
test.sh

#!/bin/sh
for i in `seq 10`; do
  echo "error$i" >&2
  echo "out$i"
done
我得到的结果如下:

$ cat log
out1
out2
error1
out3
error2
error3
out4
error4
out5
error5
out6
error6
out7
error7
out8
error8
out9
error9
out10
error10
$ cat errlog
error1
error2
error3
error4
error5
error6
error7
error8
error9
error10

有时更好,有时更糟。

添加测试脚本的输出,而不是{},我从日志中得到的是:out0 out1 out2 error0 error1 error2(我用sh test.sh替换了它,其中test.sh是我上面的测试脚本)@Cyborg-X1:这可能是缓冲问题。尝试使用
unbuffer
stdbuf
切换到行缓冲。您能进一步解释一下吗,我尝试了
stdbuf-e0-o0sh测试。sh
现在我得到了
out0error0out1out2error1error2
,(更好地扩展上面的解决方案,也更好地帮助其他来访者)@可能还有其他类型的缓冲或延迟。我不确定。我在我的机器上使用
unbuffer
得到了很好的效果。你把unbuffer放在哪里?我在最后一行之前试过了,我试着用你的解决方案调用整个脚本。但是你把它放在哪里?一次尝试日志是正确的,但err为空。另一方面,结果与之前相同。顺便说一句,在你的机器上工作很好,但不是我的机器的解决方案,而且在使用不同系统的不同docker容器时也不是很稳定。但是已经谢谢你的帮助了。以前不知道unbuffer或stdbuf。从测试脚本中添加我的输出,而不是{},我从日志中得到的是:out0 out1 out2 error0 error1 error2(我将其替换为sh test.sh,其中test.sh是我上面的测试脚本)@Cyborg-X1:这可能是缓冲问题。尝试使用
unbuffer
stdbuf
切换到行缓冲。您能进一步解释一下吗,我尝试了
stdbuf-e0-o0sh测试。sh
现在我得到了
out0error0out1out2error1error2
,(更好地扩展上面的解决方案,也更好地帮助其他来访者)@可能还有其他类型的缓冲或延迟。我不确定。我在我的机器上使用
unbuffer
得到了很好的效果。你把unbuffer放在哪里?我在最后一行之前试过了,我试着用你的解决方案调用整个脚本。但是你把它放在哪里?一次尝试日志是正确的,但err为空。另一方面,结果与之前相同。顺便说一句,在你的机器上工作很好,但不是我的机器的解决方案,而且在使用不同系统的不同docker容器时也不是很稳定。但是已经谢谢你的帮助了。以前不知道unbuffer或stdbuf。
$ cat log
out1
out2
error1
out3
error2
error3
out4
error4
out5
error5
out6
error6
out7
error7
out8
error8
out9
error9
out10
error10
$ cat errlog
error1
error2
error3
error4
error5
error6
error7
error8
error9
error10