25

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

2 Answers 2

42

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.

1
  • Thanks for the answer, seems this has generated a lot of interest. So I guess I wasn't the only one with this issue.
    – Meer Borg
    Mar 12, 2013 at 13:56
4

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).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .