如何在bash中向stdout和文件发送错误输出

时间:2022-10-16 13:58:14

If I use this

如果我用这个

cmd 2>/var/error.log

Then my error goes to that file but then I can't see on screen.

然后我的错误进入了那个文件,但是我在屏幕上看不到。

Is there any way I can simultaneously show it on screen as well as send to file?

有没有什么方法可以同时显示在屏幕上,同时发送到文件?

2 个解决方案

#1


3  

This will display both stdout and stderr on the terminal while only sending stderr to err.log:

这将在终端上显示stdout和stderr,同时只将stderr发送到error .log:

cmd 2> >(tee err.log >&2)

>(...) is process substitution. (The space between the two consecutive > is essential.) This sends stderr and only stderr to the tee command.

>(…)进程替换。(两个连续>之间的空间是必不可少的。)这将发送stderr和唯一的stderr到tee命令。

The >&2 causes the error messages remain in stderr. This would be important, for example, if this line occurs inside some script whose stdin or stderr is being redirected. (Hat tip: Chepner.)

>和2导致错误消息保持在stderr中。这一点很重要,例如,如果这一行发生在某个脚本中,该脚本的stdin或stderr正在被重定向。(提示:帽子Chepner)。

#2


0  

cmd 2>&1 | tee /tmp/error.log

#1


3  

This will display both stdout and stderr on the terminal while only sending stderr to err.log:

这将在终端上显示stdout和stderr,同时只将stderr发送到error .log:

cmd 2> >(tee err.log >&2)

>(...) is process substitution. (The space between the two consecutive > is essential.) This sends stderr and only stderr to the tee command.

>(…)进程替换。(两个连续>之间的空间是必不可少的。)这将发送stderr和唯一的stderr到tee命令。

The >&2 causes the error messages remain in stderr. This would be important, for example, if this line occurs inside some script whose stdin or stderr is being redirected. (Hat tip: Chepner.)

>和2导致错误消息保持在stderr中。这一点很重要,例如,如果这一行发生在某个脚本中,该脚本的stdin或stderr正在被重定向。(提示:帽子Chepner)。

#2


0  

cmd 2>&1 | tee /tmp/error.log