Why does this grep command not work?
Try:
service --status-all |& grep network
Command-line applications can print to two text streams known as standard out (stdout) and standard error (stderr). By default, the terminal just displays the output for both identically.
Stdout is given the number 1, and stderr is given the number 2. By default, redirection operators, like >
, |
and <
apply only to stdout, number 1.
|&
pipes both stdout and stderr together to the process on the right's standard input (stdin) stream, which makes grep
work as you expected.
I don't know why service --status-all
is printing to stderr here, but in general, having a separate stderr stream is very useful, as it lets you see errors even when stdout is silenced.
You need to redirect standard error stream (2
) to standard output (1
):
service --status-all 2>&1 | grep network
Operator >
normally redirects to file (e.g. 2>/tmp/file
). To redirect to other stream using descriptor, it needs to be preceded with &
(note no spaces between characters).