How to pipe stderr, and not 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?
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'
For the details of I/O redirection in all its variety, see the chapter on Redirections in the Bash reference manual.
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.
Or to swap the output from stderr and stdout over use:-
command 3>&1 1>&2 2>&3
This creates a new file descriptor (3) and assigns it to the same place as 1 (stdout), then assigns fd 1 (stdout) to the same place as fd 2 (stderr) and finally assigns fd 2 (stderr) to the same place as fd 3 (stdout). Stderr is now available as stdout and old stdout preserved in stderr. This may be overkill but hopefully gives more details on bash file descriptors (there are 9 available to each process).
In Bash, you can also redirect to a subshell using process substitution:
command > >(stdlog pipe) 2> >(stderr pipe)
For the case at hand:
command 2> >(grep 'something') >/dev/null
链接地址: http://www.djcxy.com/p/13474.html
下一篇: 如何管道stderr,而不是标准输出?