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 ?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
Method 3
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.
Method 4
Try this:
top | grep "my_program" 2>&1 > top.log
Method 5
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0