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
  • 727
  • 2
  • 13
  • 29

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
  • 252,262
  • 96
  • 511
  • 570
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
  • 111,086
  • 29
  • 224
  • 214