0

I'm reading my machines cpu load however the results aren't updating and the first result is constantly displayed.

#!/bin/bash
LOAD=$(ps aux|awk 'NR > 0 { s +=$3 }; END {print s"%"}')
(while true; do
echo "$LOAD"
sleep 1
done)

this returns

0.3%
0.3%
0.3%
0.3%
0.3%

even though the load has changed during this time

Lurch
  • 819
  • 3
  • 18
  • 30

2 Answers2

3

You are calculating the LOAD value just once and then printing forever that value. Instead, you have to calculate the value inside the while loop:

#!/bin/bash

while true; do
   LOAD=$(ps aux|awk 'NR > 0 { s +=$3 }; END {print s"%"}')
   echo "$LOAD"
   sleep 1
done

Test

$ ./a
81.2%
81.2%
81.1%
fedorqui
  • 275,237
  • 103
  • 548
  • 598
2

This is because the variable LOAD is evaluated just once.

You could convert it into a function instead:

LOAD() { ps aux|awk 'NR > 0 { s +=$3 }; END {print s"%"}'; }
while true; do
  LOAD
  sleep 1
done
devnull
  • 118,548
  • 33
  • 236
  • 227