如果我们的服务器上的负载过高,我正在尝试通过脚本向我发送通知。我找到了一个很好的但是当我运行时它给了我和错误,我看不出原因。
运行以下代码会出错:
第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"
答案 0 :(得分:2)
对不起,没有冒犯,但你的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"
更改如下:
uptime
解析命令awk
的输出,因为它效率低,直接从文件/proc/loadavg
获取相同的信息,一个read
内置。awk
来测试不等式,使用bc
,效率更高(并且根本不需要变量$OUT
。)$(...)
构造(更容易阅读,嵌套和更好的bash练习)。我没有测试过脚本,只是在我阅读时纠正了你的脚本。请告诉我它是否适合你。
答案 1 :(得分:0)
#!/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 $ MAIL”和-s“Server Load Alert”保持在同一行。