Pregunta

Here is my command:

top -b -n 1 | head -3 | tail -n 1 | awk '{ print $2 }'

I run a bash script which gets these details (also Load Average and memory consumption) and saves it to a file, which I use to visualise cpu load.

But the above command, shows always the same value! ~6%, no matter if the server is under heavy load or idle.

when I run:

top

It shows the same value (~6%) at the beginning, and after refresh it shows real value (eg. 80%).

How to fix that, or how to get current cpu usage, which can be used for visualisation?

¿Fue útil?

Solución 3

I didn't know it's called "iteration", using this keyword I've found a solution for the issue:

top command first iteration always returns the same result

Thank you for your help!

Otros consejos

This is because top, vmstat, iostat all in their first run collect data since the last reboot time of the system.

And the successive iterations run on the sampling period that you specify. So, in the first run of top, you will see the %idle time because from the time of reboot to the time of running top, it was that much % idle. But in next iterations, since it is busy it doesn't show any %idle.

You get try this:

top -b -n 5 -d.2 | grep "Cpu" |  tail -n 1 | awk '{ print($2)}'

or slightly shorter

top -b -n 5 -d.2 | grep "Cpu" |  awk 'NR==3{ print($2)}'

It should print something like:

48.8%us,

One possible work around would be to increase the number of iterations before you capture the result. So try something like:

top -b -n 3 | awk 'NR==3{print $2;exit}'

Note: I removed the head and tail since you can everything with awk alone.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top