if语句没有正确评估bash

时间:2012-09-09 16:40:02

标签: bash if-statement

我正在测试变量是否大于另一个变量。无论值是什么,if评估都得到相同的值。

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 }

即使值没有真正评估为真,我也会收到此输出。

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

我尝试了多种方法但无法使其正常工作。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

<按字典顺序进行比较。如果要比较整数,请使用-lt。如果您想比较浮点数,请使用bc代替test

答案 1 :(得分:1)

正如ingnacio指出的那样

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

答案 2 :(得分:0)

您在寻找数字比较或文字(字符串)比较吗?可能需要不同的操作员,具体取决于哪一个。