相对比较表达

时间:2015-04-08 07:30:31

标签: linux bash shell awk

在我的shell脚本中收集CPU利用率:

cpu=$(mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12}');
echo "CPU Usage (%): $cpu"

输出: CPU Usage (%): 0.44%

此片段遵循我的脚本中的上述两个语句:

if [ ( $cpu >= 50|bc ) -ne 0 ]; then
   /usr/sbin/sendmail "$recipients" <<EOF
   subject: $subject
   from: $from
   `date`: CPU Utilisation above 50% on $IP
EOF
echo "Mail alert triggered."
fi

问题似乎与声明中的语法相关,其中&gt; =正在进行比较。

错误:

./trialByCombat.sh: line 148: syntax error near unexpected token `$cpu'
./trialByCombat.sh: line 148: `if [ ( $cpu >= 50|bc ) -ne 0 ]; then'

我对此毫无头绪。空格,缩进,shell脚本打败了我。

2 个答案:

答案 0 :(得分:1)

由于您正在使用BASH,因此您可以使用((...))进行算术运算并避免调用bc

if (( cpu >= 50 )); then
   /usr/sbin/sendmail "$recipients" <<EOF
   subject: $subject
   from: $from
   `date`: CPU Utilisation above 50% on $IP
EOF
echo "Mail alert triggered."
fi

答案 1 :(得分:0)

将脚本更改为:

if [ $(bc <<< "$cpu <= 50") -eq 1 ]
then
   /usr/sbin/sendmail "$recipients" <<EOF
   subject: $subject
   from: $from
   `date`: CPU Utilisation above 50% on $IP
EOF
echo "Mail alert triggered."
fi

另一个样本:

AMD$ cat Script.sh
#!/bin/bash

cpu=49.9
if [ $(bc <<< "$cpu <= 50") -eq 1 ]
then
  echo "1"
fi

cpu=50.0
if [ $(bc <<< "$cpu <= 50") -eq 1 ]
then
  echo "2"
fi

cpu=50.1
if [ $(bc <<< "$cpu <= 50") -eq 1 ]
then
  echo "3"
fi


AMD$ ./Script.sh
1
2