user1601716
user1601716

Reputation: 1993

if statement not evaluating correctly bash

I am testing if a variable is greater than another variable. The if evaluation is getting the same value no matter what the values are.

COMP(){
avg=$(for avg in $(for file in $(ls /var/log/sa/sa[0123]*); do echo $file; done); do sar -r -f $avg| tail -1; done | awk '{totavg+=$4} END {print (totavg/NR)*5}');
for comp in $(sar -r -f /var/log/sa/sa08 | egrep -v "^$|Average|CPU|used" | awk '{print $5}'); do
        if [ `echo $avg` <  `echo $comp` ];
                then echo 'You have had a spike!';
                echo "COMP = $comp";
                echo "AVG = $avg";
        fi;
done }

I am getting this output even though the values are not really evaluating to true.

You have had a spike!
COMP = 41.20
AVG = 145.438
You have had a spike!
COMP = 41.20
AVG = 145.438
You have had a spike!
COMP = 41.19
AVG = 145.438
You have had a spike!  
COMP = 41.24 
AVG = 145.438

I have tried this multiple ways but can not get it working. Any ideas?

Upvotes: 0

Views: 215

Answers (3)

V H
V H

Reputation: 8587

yep as ingnacio has pointed out

average=`echo $avg`;
comp1=`echo $comp`

  if ((average)) 2>/dev/null; then
     average=$((average))
   else
     average=0;
  fi
 if ((comp1)) 2>/dev/null; then
     comp1=$((comp1))
  else
     comp1=0;
  fi

if [ $average -lt $comp1 ];then

Upvotes: 1

sureshvv
sureshvv

Reputation: 4422

Are you looking for numerical comparison or literal (string) comparison? Different operators may be needed depending on which one.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799310

< compares lexicographically. If you want to compare integers then use -lt. If you want to compare floating point numbers then use bc instead of test.

Upvotes: 1

Related Questions