如何将 stderr 重定向到 stdout 然后是管道(apt-cache)

cod*_*ers 3 bash pipe io-redirection file-descriptors

我正在尝试重定向stderrstdout然后pipe它,但我想我在这里缺少一些基本的东西。

要通过管道传输的命令和输出:

$ apt-cache show contractor
N: Can't select versions from package 'contractor' as it is purely virtual
N: No packages found
Run Code Online (Sandbox Code Playgroud)

Grep 不起作用 - 必须输出到stderr

$ apt-cache show contractor |grep virtual
Run Code Online (Sandbox Code Playgroud)

好的,让我们重定向stderrstdout

$ apt-cache show contractor 2>&1 |grep virtual
Run Code Online (Sandbox Code Playgroud)

不,这不起作用,为什么?

确认命令正在使用哪个文件描述符:

$ apt-cache show contractor 1>t ;cat t

$ apt-cache show contractor 2>t ;cat t
N: Can't select versions from package 'contractor' as it is purely virtual
N: No packages found
Run Code Online (Sandbox Code Playgroud)

确认它正在使用stderr.

与重定向的顺序有关吗?

$ apt-cache show contractor |cat 2>&1
Run Code Online (Sandbox Code Playgroud)

$ apt-cache show contractor 2>&1 |cat 2>&1
Run Code Online (Sandbox Code Playgroud)

如何重定向stderrstdoutthen pipe

use*_*777 5

那是因为apt-cache当它的标准输出不是 tty 时,它将变得“安静”并且不打印这些行。

您可以通过将其“安静度”设置为 0 来覆盖该决定:

$ apt-cache -q=0 show contractor 2>&1 | grep virtual
N: Can't select versions from package 'contractor' as it is purely virtual
Run Code Online (Sandbox Code Playgroud)