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

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

问题描述

我有一个向stdoutstderr写入信息的程序,我需要通过 stderr 的内容进行grep,而忽略 stdout .

I have a program that writes information to stdout and stderr, and I need to grep through what's coming to stderr, while disregarding stdout.

我当然可以分两个步骤进行操作:

I can of course do it in 2 steps:

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

,但我希望能够在没有临时文件的情况下执行此操作.有任何智能管道技巧吗?

but I would prefer to be able to do this without temp files. Are there any smart piping tricks?

推荐答案

首先将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当前引用的打开文件相同的描述(请参阅 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天全站免登陆