iostat returning the same values in a while loop

Hello All,

I wanted to write a script that will report me the idle percentage of the cpu. For this I was planning on using "iostat".

When I run iostat with its -w parameter, the cpu idle values change ("iostate -t proc -w 1"). This is ok. It continuously prints the proc parameters every second. The values show change in the cpu idle percentage. As can be seen below

tty cpu
tin tout us ni sy in id
3 56 8 0 3 0 88
1 81 4 0 3 0 93
0 27 3 0 2 0 95
0 27 3 0 3 0 94
1 27 3 0 2 0 94

But when I do this in a loop, the values do not change. I have created a loop like so...

while test "1"=="1"; do iostat -t proc; sleep 0.8; done

This does invoke iostat. But the values do now change. Here is the output

tty cpu
tin tout us ni sy in id
2 61 8 0 3 0 88
tty cpu
tin tout us ni sy in id
2 61 8 0 3 0 88
tty cpu
tin tout us ni sy in id
2 61 8 0 3 0 88
tty cpu
tin tout us ni sy in id
2 61 8 0 3 0 88
tty cpu
tin tout us ni sy in id
2 61 8 0 3 0 88
tty cpu
tin tout us ni sy in id
2 61 8 0 3 0 88

Why would the values not change? I am confused on this behavior...

Regards
 
Ugh, I can't read, from iostat(8):
Code:
The first statistics that are printed are averaged over the system uptime.
Does that mean, we should at least take 2 readings, possibly specifying a suitable wait time. Like so

Code:
iostat -w 0.1 -c 2

Here getting 2 readings with 0.1 sec apart, and taking the last reading would maybe give me a fairly close reading. Or maybe average the two readings maybe.
 
Here getting 2 readings with 0.1 sec apart, and taking the last reading would maybe give me a fairly close reading. Or maybe average the two readings maybe.
First one is average over all uptime so adding it up will break current readings. If you really need it in a while loop, may be something like this (going with your idea)?
Code:
while true; do iostat -w 0.01 -c 2 | tail -1; sleep 1; done
 
First one is average over all uptime so adding it up will break current readings. If you really need it in a while loop, may be something like this (going with your idea)?
Code:
while true; do iostat -w 0.01 -c 2 | tail -1; sleep 1; done
Or maybe take 3 readings and average the last 2. That might be better.
 
If you insist on using iostat(8), you can pipe into the entire while statement, specifically read:
Bash:
iostat -t proc -w 1 | while read tty_input tty_output cpu_user cpu_nice cpu_system cpu_interrupt cpu_idle
do
    # `iostat(8)` regularly prints a column header.
    expr "${cpu_idle}" : '[[:digit:]]' >&- || continue
    
    printf 'I am %3d%% idle.\n' ${cpu_idle}
done
 
Back
Top