Parsing the output from top

Guys can you help me fix this parse error.

Here's my script.

#!/bin/bash
# Set up limit below

NOTIFY="6.0% us 6.1% us 6.2% us 6.3% us 6.5% us 6.6% us 6.7% us 6.8% us 6.9% us 7.0% us"

# CPU Usage every minute
TOP="$(top -b -n2 -d 00.20 |grep Cpu|tail -1 | awk -F ":" '{ print $2 }' | cut -d, -f1)"

# compare it with last usage
RESULT=$(echo "$TOP > $NOTIFY" | bc)

# if load >= 80.0% create a file /home/scripts/loadavg.txt

if [ "$RESULT" = "6.0% us 6.1% us 6.2% us 6.3% us 6.5% us 6.6% us 6.7% us 6.8% us 6.9% us 7.0% us" ]; then
        echo $RESULT "cpu usage" >>  /home/scripts/loadavg.txt

This will output the cpu usage then compare on the notify now i'm getting this error

-bash-3.00$ sh -x cpu 
+ NOTIFY='6.0% us 6.1% us 6.2% us 6.3% us 6.5% us 6.6% us 6.7% us 6.8% us 6.9% us 7.0% us'
++ top -b -n2 -d 00.20
++ grep Cpu
++ tail -1
++ awk -F : '{ print $2 }'
++ cut -d, -f1
+ TOP='  6.7% us'
++ echo '  6.7% us > 6.0% us 6.1% us 6.2% us 6.3% us 6.5% us 6.6% us 6.7% us 6.8% us 6.9% us 7.0% us'
++ bc
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
(standard_in) 1: parse error
+ RESULT=
+ '[' '' = '6.0% us 6.1% us 6.2% us 6.3% us 6.5% us 6.6% us 6.7% us 6.8% us 6.9% us 7.0% us' ']'

Thanks in advance.

The parse error comes from "bc". The script executes

echo '  6.7% us > 6.0% us 6.1% us 6.2% us 6.3% us 6.5% us 6.6% us 6.7% us 6.8% us 6.9% us 7.0% us' | bc

which is not a correct input for "bc". On the other hand it is not quite clear, what you would like to achieve with the script. The field you extract from "top" output has little to do with load average.

1 Like

If you are on linux it's better to see load average from /proc/loadavg. You can do it something like this:

while true; do
  loadavg=`cat /proc/loadavg`
  sleep 1 # or some other time
  # do something with $loadavg
done

See man 5 proc

1 Like

If your not on linux try looking at uptime for a quick summary of load, or sar -u 2 1

1 Like