Bash脚本错误。意外令牌附近的语法错误

时间:2012-12-04 09:03:24

标签: linux bash

如果我们的服务器上的负载过高,我正在尝试通过脚本向我发送通知。我找到了一个很好的但是当我运行时它给了我和错误,我看不出原因。

运行以下代码会出错:

  

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

2 个答案:

答案 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"

更改如下:

  • 使用小写变量名称,因为大写变量名称被认为是糟糕的bash实践。
  • 不要使用数百万个管道,子shell和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”保持在同一行。