<分区>
尝试运行一个产生大量标准输出和标准错误的命令。 需要一种方法来过滤大多数 stderr 消息。
有点像
command 1> grep "a" 2> grep "b"
替代方法如何只 grep stderr 但也看到 stdout。
<分区>
尝试运行一个产生大量标准输出和标准错误的命令。 需要一种方法来过滤大多数 stderr 消息。
有点像
command 1> grep "a" 2> grep "b"
替代方法如何只 grep stderr 但也看到 stdout。
最佳答案
做:
{ command 2>&1 1>&3 3>&- | grep "b"; } 3>&1 1>&2 | grep "a"
注:以上内容改编自antak's answer to "pipe stdout and stderr to two different processes in shell script?" , 用 grep
s 替换它更抽象的名字。有关其工作原理,请参阅该答案。
(尽管如此,需要 grep
的懒惰编码人员可能更喜欢像这样的更具体的答案。)
区分 stdout 和 stderr 的有用工具是 annotate-output
, (安装 "devscripts" package ),它将 stderr 和 stdin 连同有用的小前缀一起发送到 stdout:
annotate-output wc -c /bin/bash /bin/nosuchshell
输出:
00:29:06 I: Started wc -c /bin/bash /bin/nosuchshell
00:29:06 E: wc: /bin/nosuchshell: No such file or directory
00:29:06 O: 1099016 /bin/bash
00:29:06 O: 1099016 total
00:29:06 I: Finished with exitcode 1
可以使用 sed
、awk
甚至 tee
和一些 grep
单独解析该输出
关于bash - 如何通过单独的 grep 过滤器发送 stderr 和 stdout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48728356/