0

I have a flaky Internet connection, so I decided to make a bash script that would alert me whenever the internet is back. This is the script:

#!/bin/bash
# set -x


while [ 1 ];do
  STATUS_CURRENT=$(ping -q -w 1 -c 1 google.com > /dev/null && echo connected || echo disconnected)
  if [[ $STATUS_CURRENT == "connected"  &&  $STATUS_LAST != "connected" ]];then
        aplay /home/user/bin/online.wav
        notify-send "We've connected"

 elif [[ $STATUS_CURRENT == "disconnected"  &&  $STATUS_LAST == "connected"  ]];then
       aplay /home/user/bin/offline.wav
       notify-send "Disconnected now"
  fi

   STATUS_LAST=$STATUS_CURRENT
   sleep 2
done

I have this added in /etc/rc.local to have it executed on startup. The problem with this script is that it sometimes fail. Even when there's Internet connectivity, the script sends notification saying it's disconnected (immediately followed by the "connected" message).

How can I avoid this problem? Does it have something to do with the fact that ping is slow to fail? How can the script be improved?

Joseph John
  • 510
  • 1
  • 5
  • 21
  • You should at least ping more than once. As in, increase the `-c` value – arco444 Jun 30 '15 at 09:57
  • @arco444: Thanks, I did try that before, but it only caused the script to not work at all. I'm not sure why that is, though. – Joseph John Jun 30 '15 at 10:16
  • You'd need to also increase the `-w` value. Maybe this is the source of your problem anyway, it's certainly possible you'll get the occasional reply that takes >1 sec. If the script receives a single one of these it will perceive the connection to be down. – arco444 Jun 30 '15 at 11:32

1 Answers1

0

With "netcat" it works very stable for me

#!/bin/bash

status=0

do_on=("/home/user/bin/online.wav"
       "We've connected")

do_off=("/home/user/bin/offline.wav"
        "Disconnected now")

while [ 1 ] ;do
    nc -zw 2 google.de 80
    ret="$?"

    if [ "$ret" = 0 -a "$status" = 0 ] ;then
        aplay ${do_on[0]}
        notify-send ${do_on[1]}
        status=1

    elif [ "$ret" -ne 0 -a "$status" = 1 ] ;then
        aplay ${do_off[0]}
        notify-send ${do_off[1]}
        status=0 ;fi

    sleep 2 ;done

You should test your DNS server in advance

cheers Karim

foodude
  • 19
  • 3