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?