Bash

錯誤:應為整數表達式

  • June 20, 2014

我編寫了一個腳本來確定伺服器上的平均負載,如下所示:

#!/bin/bash

loadavg=`top -b -n1 | grep -i load | awk -F, '{print$4}'| awk -F: '{print $2}'`

if [ "${loadavg}" -le  1 ]
then
echo "OK - Load Average = ${loadavg} | Load_Average=${loadavg}"
exit 0;
elif [ "${loadavg}" -gt 1 ] && [ "${loadavg}" -le 2 ]
then
echo "WARNING - Load Average = ${loadavg} | Load_Average=${loadavg}"
exit 1;
elif [ "${loadavg}" -gt 2 ]
then
echo "CRITICAL - Load Average = ${loadavg} | Load_Average=${loadavg}"
exit 2;
else
echo "UNKNOWN - Load Average = NaN | Load_Average=NaN"
fi

執行腳本時,會顯示以下錯誤:

./loadavg.sh
./loadavg.sh: line 5: [:  0.06: integer expression expected
./loadavg.sh: line 9: [:  0.06: integer expression expected
./loadavg.sh: line 13: [:  0.06: integer expression expected
UNKNOWN - Load Average = NaN | Load_Average=NaN

bash(與ksh93or zsh1相反)不能進行浮點運算。awk不過可以,所以你可以在awk.

此外,您不需要使用top(並等待 1 秒)來獲得負載。獲取負載的規範方法是從uptime.

uptime | awk '{load=+$(NF-2)}
 load > 2 {print "CRITICAL: " load; exit 2}
 load > 1 {print "WARNING: " load; exit 1}
 {print "OK: " load; exit 0}
 END {if (!NR) {print "UNKNOWN"; exit 3}'
exit

1不過,zsh您需要使用(( loadavg > 2 ))代替[ "$loadavg" -gt 2 ]語法來比較非整數

引用自:https://unix.stackexchange.com/questions/138226