Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Using the top command with redirection works fine:

top > top.log

Now I want to use grep to filter a certain line:

top | grep "my_program" > top.log

But the log file will remain empty. But grep delivers an output when using

top | grep "my_program"

Where my_program has to be replaced by a running program to see some output.

Why does my approach not work ? And how can I fix it ?

share|improve this question

migrated from stackoverflow.com Sep 27 '12 at 0:48

This question came from our site for professional and enthusiast programmers.

I just tried it, and it works for me. However, you should probably look at -b option to top or using ps instead. – Lev Levitsky Sep 26 '12 at 19:38
-b did not solve my problem, but solved some encoding problems. Thank you. – John Threepwood Sep 26 '12 at 20:09
up vote 9 down vote accepted

I get the same behavior that you describe. On Ubuntu 11.10

top | grep "my_program" > top.log

does not produce any output.

I believe the reason for this is that grep is buffering its output. To tell GNU grep to spit out output line-by-line, use the --line-buffered option:

top | grep --line-buffered "my_program" > top.log

See also this SO question for other potential solutions.

share|improve this answer
+1 --line-buffered solves the problem. – Victor Hugo Sep 26 '12 at 20:01
Thank you, this solves the problem for me, too. The -b option is still a good advice from Lev Levitsky, too. That solved some encoding problems with the log file. – John Threepwood Sep 26 '12 at 20:08

you should use:

top -n 1 | grep "blah" > top.log

the "-n 1" runs top for one iteration and then quits instead of continually updating every few seconds

since you're just looking for one line though ps would be a better tool to use.

share|improve this answer

Try this:

top | grep "my_program" 2>&1 > top.log

What means 2>&1?

share|improve this answer

Although both work for me, I think Lev Levitsky's advice is the correct one. Use the -b argument.

There is a good chance that output redirection is the problem and that you're not getting anything through stdout, so try this instead:

top -b 2>&1 | grep "my_program" > top.log

Do note that you might have problems with output buffering aswell. Your shell won't constantly write to the file so it could take a while for top.log to fill.

share|improve this answer

My workaround for this problem was:

while :;do top -b -n 1 | grep "my_program" >> top.log;done &

By this way I could have a running monitor in the background for my_program and keep all results in the file top.log.

share|improve this answer

Your Answer


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