我正在尝试通过脚本在我的服务器上负载过高时通过电子邮件向我发送通知。我找到了一个很好的,但是当我运行它时它给了我和错误,我看不出为什么。
运行下面的代码会出现错误:
第 13 行:意外标记"fi"附近的语法错误
不过,我认为我必须正确布局。谢谢!
#!/bin/bash
THR=10
MAIL="address@domain.com"
VAR=`uptime|awk -F, '{print $4}'|awk '{print $3}'`
OUT=`echo "$VAR $THR" | awk '{if ($1 > $2) print "yes"; else print "no"}'`
if [ "$VAR" == "" ]
then
# it's within the first 24 hours of uptime
VAR=`uptime|awk -F, '{print $3}'|awk '{print $3}'`
OUT=`echo "$VAR $THR" | awk '{if ($1 > $2) print "yes"; else print "no"}'`
fi
if [ "$OUT" == "yes" ]
then
echo "The current load $VAR is greater than the threshold $THR" | mail $MAIL
-s "Server Load Alert"
echo "Alert generated because $VAR is greater than $THR"
else
echo "No alert as $VAR > $THR"
fi
echo "load = $VAR"
对不起,没有冒犯,但你的 bash 风格很糟糕!
这是一个更好的版本:
#!/bin/bash
thr=10
mail="address@domain.com"
read var _ < /proc/loadavg
if (( $(bc -l <<< "$var>$thr") )); then
echo "The current load $var is greater than the threshold $thr" | mail "$mail" -s "Server Load Alert"
echo "Alert generated because $var is greater than $thr"
else
echo "No alert as $var <= $thr"
fi
echo "load = $var"
更改如下:
- 使用小写变量名称
- ,因为大写变量名称被认为是不好的 bash 做法。
- 不要使用数百万个管道、子壳和
awk
来解析命令uptime
输出,因为它效率低下,相同的信息直接从文件/proc/loadavg
获取,内置read
。 - 不要使用
awk
来测试不等式,使用bc
,它更有效(而且你根本不需要变量$OUT
)。 - 没有反引号!改用
$(...)
结构(更易于阅读、嵌套和更好的 bash 练习)。
我没有测试脚本,只是在阅读时更正了您的脚本。请告诉我它是否适合您。
#!/bin/bash
THR=10
MAIL="address@domain.com"
VAR=`uptime|awk -F, '{print $4}'|awk '{print $3}'`
OUT=`echo "$VAR $THR" | awk '{if ($1 > $2) print "yes"; else print "no"}'`
if [ "$VAR" == "" ]
then
# it's within the first 24 hours of uptime
VAR=`uptime|awk -F, '{print $3}'|awk '{print $3}'`
OUT=`echo "$VAR $THR" | awk '{if ($1 > $2) print "yes"; else print "no"}'`
fi
if [ "$OUT" == "yes" ]
then
echo "The current load $VAR is greater than the threshold $THR" | mail $MAIL -s "Server Load Alert"
echo "Alert generated because $VAR is greater than $THR"
else
echo "No alert as $VAR > $THR"
fi
echo "load = $VAR"
这对我有用。我更改了"邮件$MAIL"和-s"服务器负载警报"保持在同一行。