1

如果我们的服务器上的负载太高,我正在尝试通过脚本向我发送电子邮件通知。我找到了一个好的,但是当我运行它时它给了我和错误,我不明白为什么。

运行下面的代码会出现错误:

第 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"
4

2 回答 2

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"

变化如下:

  • 使用小写的变量名,因为大写的变量名被认为是不好的 bash 做法。
  • 不要uptime使用数百万个管道、子shell 和awks 来解析命令的输出,因为它效率低下,相同的信息是直接从文件中获得的/proc/loadavg,带有read内置函数。
  • 不要awk用来测试不等式,使用bc,它更有效(而且你根本不需要变量$OUT)。
  • 没有反引号!改为使用$(...)构造(更易于阅读、嵌套和更好的 bash 练习)。

我没有测试脚本,只是在阅读时更正了你的脚本。请告诉我它是否适合你。

于 2012-12-04T09:45:29.957 回答
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”保持在同一行。

于 2012-12-04T09:24:32.110 回答