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何百万ものパイプ、サブシェル、およびsを使用してコマンドの出力を解析しないでください。これは非効率的であり、同じ情報が組み込みawkのファイルから直接取得されます。/proc/loadavgread
  • 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「ServerLoadAlert」が同じ行に表示されるように変更しました。

于 2012-12-04T09:24:32.110 に答える