Why does 'top | grep > file' not work?

JaycePark picture JaycePark · Aug 30, 2013 · Viewed 12.1k times · Source

I tested the following command, but it doesn't work.

$> top -b -d 1 | grep java > top.log

It doesn't use standard error. I checked that it uses standard output, but top.log is always empty. Why is this?

Answer

devnull picture devnull · Aug 30, 2013

By default, grep buffers output which implies that nothing would be written to top.log until the grep output exceeds the size of the buffer (which might vary across systems).

Tell grep to use line buffering on output. Try:

top -b -d 1 | grep --line-buffered java > top.log