Ubuntu – Why does this grep command not work

grepservices

When I try to use grep in this fashion:

service --status-all | grep network

It still lists all the services even though I piped it into grep to restrict it to the "network" string only


After the Fact:

Noticed this article that explains why the command behaves this way, that's what I like about linux, there is always a good reason, but not necessary intuitive

Best Answer

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.