Bash逻辑检查-使用嵌套的“While”循环重复;如果是“那么”;声明
我正在编写一个脚本来监视我的sip中继并尝试修复它。如果它六次都未能解决此问题,请重新启动服务器。cron通过Bash逻辑检查-使用嵌套的“While”循环重复;如果是“那么”;声明,bash,scripting,Bash,Scripting,我正在编写一个脚本来监视我的sip中继并尝试修复它。如果它六次都未能解决此问题,请重新启动服务器。cron通过@reboot调用脚本。我第一次使用嵌套的While循环,但它不能正常工作,因此我切换到一个永无止境的While循环,其中包含两个嵌套的If循环,以执行脚本的功能 我想知道是否有人可以快速看一下,看看我攻击它的方式是否合理,是否合乎逻辑 谢谢, 目前的脚本: #!/bin/bash pwd="/srv/scripts" count=0 echo "Script Started on $
@reboot
调用脚本。我第一次使用嵌套的While循环
,但它不能正常工作,因此我切换到一个永无止境的While循环
,其中包含两个嵌套的If循环
,以执行脚本的功能
我想知道是否有人可以快速看一下,看看我攻击它的方式是否合理,是否合乎逻辑
谢谢,
目前的脚本:
#!/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
无需在
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
我可能还会将所有日志通知收集到一个日志文件中,并使用更传统的日志格式,在每条消息前加上时间戳和脚本名称
如果看到成功,计数器是否应重置为零?由于在错误的时间断开网络电缆而重新启动服务器似乎是您希望避免的事情。这似乎没问题。我只是无法理解
var=init
的用法,我不确定这是否是对SE的某种违反,因为它目前没有任何问题,但我希望得到逻辑方面的反馈,我从来没有真正做过嵌套循环。我只是使用var=init
将变量设置为除“已注册”外的任何值,也许我本可以不设置,但我习惯于在早期设置变量。这有点“免费”,如果有人对自己的编程知识有足够的信心来回答逻辑是正确的
@Simonare你应该看到嵌套的While Loops
版本,读起来真是一场噩梦,嵌套的If/Then
it sorta click是正确的方法。您的解决方案不包括嵌套的If。但你可以利用它course@Simonareif/then
嵌套在While循环中,这就是我的意思。