通过grep重定向shell输出 [英] Redirecting shell output via grep
问题描述
我有一个node.js脚本,我希望stdout和stderr都能转到日志文件,但我想先通过grep传递stdout和stderr。
这是有效的:
节点a.js> a.log 2>& 1
但这不是:
节点a.js | grep错误> a.log 2>& 1
它不向文件输出任何内容,但更糟糕的是它开始输出stdout / stderr到再次终端,这是错的。
我尝试过:
(参见原始问题描述。)
I have a node.js script and I want both stdout and stderr to go to a log file, but I want to pass the stdout and stderr through grep first.
This works:
node a.js > a.log 2>&1
But this doesn't:
node a.js | grep "error" > a.log 2>&1
It doesn't output anything to the file, but worse it starts outputting stdout/stderr to the terminal again, which is just wrong.
What I have tried:
(See original question description.)
推荐答案
只需将stderr
重定向到管道到 grep 之前的stdout
:
Just redirectstderr
tostdout
before piping to grep:
node a.js 2>&1 | grep "error" > a.log
使用 bash 时,会有以上简写:
When using bash, there is a shorthand for the above:
node a.js |& grep "error" > a.log
|&
, stdout
并且第一个命令的 stderr
被传送到第二个命令。请参阅 Bash参考手册 [ ^ ]。
With |&
, stdout
and stderr
of the first command are piped to the second. See the Bash Reference Manual[^].
这篇关于通过grep重定向shell输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!