Bash – Why Grep Doesn’t Work with Redirection

bashgrep

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 ?

Best Answer

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.

Related Question