我如何通过管道 stderr 而不是 stdout? [英] How can I pipe stderr, and not stdout?

查看:32
本文介绍了我如何通过管道 stderr 而不是 stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序将信息写入stdoutstderr,我需要用grepstderrcode>,将 stdout 放在一边.

I have a program that writes information to stdout and stderr, and I need to process the stderr with grep, leaving stdout aside.

使用临时文件,可以分两步完成:

Using a temporary file, one could do it in two steps:

command > /dev/null 2> temp.file
grep 'something' temp.file

但是如何在没有临时文件的情况下使用一个命令和管道来实现这一点?

But how can this be achieved without temp files, using one command and pipes?

推荐答案

首先将 stderr 重定向到 stdout——管道;然后将 stdout 重定向到 /dev/null(不改变 stderr 的去向):

First redirect stderr to stdout — the pipe; then redirect stdout to /dev/null (without changing where stderr is going):

command 2>&1 >/dev/null | grep 'something'

有关各种 I/O 重定向的详细信息,请参阅关于 重定向.

For the details of I/O redirection in all its variety, see the chapter on Redirections in the Bash reference manual.

请注意,I/O 重定向的顺序是从左到右解释的,但管道是在解释 I/O 重定向之前设置的.诸如 1 和 2 之类的文件描述符是对打开文件描述的引用.2>&1 操作使文件描述符 2 aka stderr 引用与文件描述符 1 aka stdout 当前引用的相同的打开文件描述(请参阅 dup2()open()).操作 >/dev/null 然后更改文件描述符 1,以便它引用 /dev/null 的打开文件描述,但这并没有改变事实文件描述符 2 指的是文件描述符 1 最初指向的打开文件描述——即管道.

Note that the sequence of I/O redirections is interpreted left-to-right, but pipes are set up before the I/O redirections are interpreted. File descriptors such as 1 and 2 are references to open file descriptions. The operation 2>&1 makes file descriptor 2 aka stderr refer to the same open file description as file descriptor 1 aka stdout is currently referring to (see dup2() and open()). The operation >/dev/null then changes file descriptor 1 so that it refers to an open file description for /dev/null, but that doesn't change the fact that file descriptor 2 refers to the open file description which file descriptor 1 was originally pointing to — namely, the pipe.

这篇关于我如何通过管道 stderr 而不是 stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆