Bash逻辑检查-使用嵌套的“ IF Then”语句重复While循环

时间:2018-12-10 09:19:03

标签: bash scripting

我正在编写一个脚本来监视我的Sip干线并尝试对其进行修复。如果6次未能解决问题,请重新启动服务器。 cron通过@reboot调用了该脚本。我首先嵌套了While Loops,但是无法正常工作,所以我切换到了一个永无休止的While Loop,其中有两个嵌套的If Loops以执行脚本的功能。

我想知道是否有人可以快速浏览一下,看看我的攻击方式是否合理且合乎逻辑。

谢谢

目前的脚本:

#!/bin/bash

pwd="/srv/scripts"
count=0
echo "Script Started on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"

start=start
while [ $start = "start" ]; do

sleep 420

var="$(asterisk -rx "pjsip show registrations" | grep -o Registered)"

    if [ "$var" != "Registered" ]; then
        amportal restart
        count=$(( $count + 1 ))
        echo "Trunk Failure on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"
    fi

    if [ "$count" -gt 5 ]; then  
        echo "Server Reboot due to Failure.Count=$count on $(date -u)" >> "$pwd/reboot.notification"  
        reboot    
    fi
done

1 个答案:

答案 0 :(得分:1)

无需在while循环中使用变量,也无需将grep的输出捕获到变量中。

#!/bin/bash

pwd="/srv/scripts"
count=0
echo "Script Started on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"

# No need for a variable here
while true; do
    # Fix indentation
    sleep 420

    # Again, no need for a variable; use grep -q
    if ! asterisk -rx "pjsip show registrations" | grep -q Registered
    then
        amportal restart
        count=$(( $count + 1 ))
        echo "Trunk Failure on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"
    fi

    if [ "$count" -gt 5 ]; then  
        echo "Server Reboot due to Failure.Count=$count on $(date -u)" >> "$pwd/reboot.notification"  
        reboot    
    fi
done

我也许还会将所有日志通知收集到一个日志文件中,并使用更传统的日志格式,并在每个消息之前加上时间戳和脚本名称。

如果看到成功,计数器应该重置为零吗?由于您在错误的时间断开了网络电缆的连接而使服务器重新启动似乎是您要避免的事情。

相关问题