1

I'am developing bash script, which enabling/disabling ddos protection from cloudflare. Here is my code:

#!/bin/bash

PERC=$(grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage}');

if [[ "$PERC" -gt 50 ]]
    then
        echo 'high load';
    else
        echo 'normal load';
fi

I have 2 issues: 1. PERC are always the same result 2. seems like result of PERC variable incorrect, because of error '-bash: [[: 41.8679: syntax error: invalid arithmetic operator (error token is ".8679")'

What's wrong with my code?

1 Answers1

3

Using point-in-time CPU load can lead to very misleading results – say you happen to catch it when it's in the middle of refreshing a cache which take 100% CPU for 0.2 seconds…

Furthermore bash can only handle integer arithmetic. You can use a tool like bc to do more complex operations. Alternatively, given you probably don't care about the decimal value, you could strip it off (cut -d. -f 1)

Have you considered using the long-established load average concept that's been in UNIX for a long time?

Also bear in mind that the arithmetic (despite not working) may not work on other platforms:

/proc/stat kernel/system statistics. Varies with architecture. Common entries include:

          cpu  3357 0 4313 1362393
                 The amount of time, measured in  units  of  USER_HZ  (1/100ths  of  a  second  on  most  architectures,  use
                 sysconf(_SC_CLK_TCK) to obtain the right value), that the system spent in various states

...

foo
  • 76
  • 5