Reputation: 9
I'm trying to slow down my infinite loop if CPU load exceeds certain limit, but, its just not working out right, below is the code. The if condition always results true
c=1
while [ $c -le 1 ]
do
#echo "Welcome $c times"
#php BALHABLH.php
IN=$(cat /proc/loadavg);
set -- "$IN"
IFS=" "; declare -a Array=($*)
echo "${Array[@]}"
echo "${Array[0]}"
echo "${Array[1]}"
#var = ${Array[1]}
x=$(expr "${Array[1]}" )
if [ $x > 0.91 ]
then
echo "CPU LOAD > 0.91"
sleep 2
fi
(( c++ ))
done
Upvotes: 0
Views: 1171
Reputation: 33327
Bash only handles integers. To handle floats pipe to bc
like this:
[ $(echo " $x > 0.91" | bc -l) -eq 1 ]
bc
returns 1
if the comparison is true. We compare with 1 (using the -eq operator).
Validation
$ cat test.sh
#!/bin/bash
x="$1"
if [ $(echo " $x > 0.91" | bc -l) -eq 1 ]; then
echo greater;
else
echo smaller;
fi
$ ./test.sh 0.5
smaller
$ ./test.sh 1.5
greater
You can also simplify your script a bit like this:
#!/bin/bash
c=10
for (( i=1;i<=c;i++ )); do
load=$(awk '{print $2}' /proc/loadavg)
echo "$i: load is $load"
if (( $(echo "$load > 0.91" | bc) == 1 )); then
echo "CPU LOAD > 0.91"
sleep 2
fi
done
Upvotes: 0
Reputation: 9926
Bash cannot use floating point arithmetic. You could do something like this:
if [ $( echo "$x > 0.91" | bc ) -eq 1 ]; then
Upvotes: 0
Reputation: 274592
You need to use bc
for floating point comparison and use (( ... ))
for arithmetic expressions:
if (( $(bc -l <<< "$x > 0.91") == 1 ))
Also don't use cat
, use:
IN=$(</proc/loadavg)
Upvotes: 2