Question

A command like top | grep chromium is giving me a time trend over CPU and memory load to STDOUT. I am trying to pipe this output to a file with top | grep chromium >> load.log which fails (no error but load.log stays empty).

  • Is the problem the time varying output of top?
  • How can I solve this issue without using external tools solely using Bash?
  • How can I adjust the update time?
Was it helpful?

Solution

top | grep --line-buffered chromium >> load.log

When grep writes to a tty its output is line buffered. When it's redirected to a file its output is fully buffered, meaning it only flushes every 4096 bytes. The --line-buffered option overrides this behavior, forcing it to flush stdout after every line.

This behavior isn't unique to grep; it can happen with any standard C program that uses libc. You can use stdbuf to force an arbitrary program to be line-buffered.

top | stdbuf -oL grep chromium >> load.log
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top