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 ?

  • 2
    I just tried it, and it works for me. However, you should probably look at -b option to top or using ps instead. Sep 26, 2012 at 19:38
  • -b did not solve my problem, but solved some encoding problems. Thank you.
    – John Threepwood
    Sep 26, 2012 at 20:09

5 Answers 5


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.

  • 3
    +1 --line-buffered solves the problem.
    – Victor Hugo
    Sep 26, 2012 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, 2012 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.


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.


Try this:

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

What means 2>&1?


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.

You must log in to answer this question.