3

When I run this command in Linux:

$ top -b -d 20 | grep "load average" -A 20 > top.log

top.log is always empty.

But when I run this command:

$ top -b -d 20 | grep "load average" -A 20 | tee top.log

then top.log has contents.

If I don't want to use tee (because I don't want the output to be displayed onto the console), how do I correct the first command so that top.log is updated?

My machine uses CentOS Linux 7 (Core).

  • weird. In my Cento7 machine, both commands work well. – JinChin Mar 27 at 10:29
  • 1
    if you want only load average, why not use uptime ? – Archemar Mar 27 at 10:29
  • @Archemar What is the -A option of grep for? – Uncle Billy Mar 27 at 10:33
  • @Archemar @UncleBilly, i'm using a trick for limiting the amount of entries returned by top. – kurt Mar 27 at 10:36
  • @UncleBilly Ah, yes that is the catch ... – Archemar Mar 27 at 10:38
3

You should use the --line-buffered option of grep (since your question is tagged "centos", you're most certainly using GNU grep).

By default, grep will only use line buffering when the output is a terminal (just like stdio functions: printf, puts, etc). The --line-buffered option is overriding that. GNU coreutils also has a stdbuf(1) wrapper that should work with any dynamically linked program which is using stdio.

-1

You can use cat /proc/loadavg at intervals. Why pull it from top? It is intended for active monitoring (mostly), and will always use more resources than a fast read of loadavg. For the process listing, just use ps, and sort with the —sort flag. E.g.

( while true ; do cat /proc/loadavg ; ps -aux | sort -nrk 3,3 | head -n 20 ; sleep 3 ; done ; ) | pipe ...

or

( while true ; do cat /proc/loadavg ; ps -Ao user,uid,pid,comm,pcpu,tty —sort=-pcpu —no-headers | head -n 20 ; sleep 3 ; done ; ) | pipe ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.