Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers 2

up vote 32 down vote accepted

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.

share|improve this answer
    
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 '13 at 13:56
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.