Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

2  
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
add comment

4 Answers 4

up vote 4 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
add comment

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
add comment

Try this:

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

What means 2>&1?

share|improve this answer
add comment

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
add comment

Your Answer

 
discard

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