Ann*_*a M 3 c unix redirect stderr tee
我需要在bash脚本中执行一个命令(在freebsd6上),我需要将命令的stderr和stdout发送到控制台,一个日志文件和一个bash变量.
所以,没有任何重定向,我想要的是:
result=`./command | tee output.log`
Run Code Online (Sandbox Code Playgroud)
如果我按原样运行,只有stderr进入控制台,只有stdout将它同时输出到output.log文件和$ result变量.我理解为什么会这样,但许多尝试不同的重定向都无法将两个流发送到所有三个位置.
如何将stderr和stdout发送到所有三个位置?
result=`./command 2>&1 | tee output.log | tee /dev/tty`
Run Code Online (Sandbox Code Playgroud)
[编辑]
正如nm在注释中指出的那样,tee接受多个参数:
result=`./command 2>&1 | tee output.log /dev/tty`
Run Code Online (Sandbox Code Playgroud)
[第二次编辑]
在评论中借用Chris的想法,您也可以将输出发送到stderr:
result=`./command 2>&1 | tee /tmp/foo.log >(cat 1>&2)`
Run Code Online (Sandbox Code Playgroud)
要做到你想要的,我发现的最好的是:
exec 3>&1 ; result=`./command 2>&1 | tee /tmp/foo.log >(cat 1>&3)` ; exec 1>&3
Run Code Online (Sandbox Code Playgroud)
(这里的整个问题是反引号在内部任何内容之前重定向stdout得到执行.所以这行保存并恢复旧的stdout作为描述符3,这可能是也可能不是一个好主意......)