仅当ping关闭时才会继续Bash

时间:2017-03-07 14:24:02

标签: linux bash loops if-statement

我正在尝试创建一个只在ping无响应时才会继续运行的脚本。

我遇到了两个主要问题。一个是它需要2个CTL-C命令来结束脚本,另一个问题是脚本永远不会结束并且需要杀死。

以下是我的尝试;

rc=0
until [ $rc -gt 0 ]
do
      ping 69.69.69.69 > /dev/null 2>&1
      rc=$?
done

## Here will be the rest of code to be executed

我觉得上面的这个非常接近,因为它需要2个CTL-C命令并继续。 这是我在SO上找到的但根本无法开始工作的东西。

counter=0
while [ true ]
do
  ping -c 1 69.69.69.69 > /dev/null 2>&1
    if [ $? -ne 0 ] then
        let "counter +=1"
    else
        let "counter = 0"
    fi
    if [ $counter -eq 10 ] then
        echo "Here should be executed once pinging is down"
    fi
done

非常感谢任何帮助,谢谢。

2 个答案:

答案 0 :(得分:3)

试试这个:

while ping -c 1 -W 20 "$host" >& /dev/null
do
  echo "Host reachable"
  sleep 10  # do not ping too often
done
echo "Host unreachable within 20 seconds"

答案 1 :(得分:1)

有一些问题: 首先,if语句是错误的 使用此格式

if [ $? -ne 0 ] then;

或其他格式

if [ $? -ne 0 ]
then

其次我怀疑你的ping不是超时

ping -c 1 -w 2 69.69.69.69 > /dev/null 2>&1

可能有帮助

第三,你的循环将继续递增计数器,即使在10之后。你可能想在10之后退出

while [ $counter -le 10 ]

如果您在执行某些操作时感到满意,如果在x秒之后ping没有任何响应,则可以全部压缩(下例中为10秒):

ping -c 1 -w 10 69.69.69.69 >/dev/null 2>&1 || echo "run if ping timedout without any response"
相关问题