AKor
AKor

Reputation: 8892

Creating a shell script to check network connectivity

I'm making a simple shell script that runs an infinite loop, then if the output of the ping command contains "time" (indicating that it pinged successfully) it should echo "Connected!", sleep 1, and clear. However, I get no output from my script.

#!/bin/bash
while :
do
    if [[ $(ping google.com) == *time* ]]; 
    then
        echo -en '\E[47;32m'"\033[1mS\033[0m"
        echo "Connected!"
    else
        echo -en '\E[47;31m'"\033[1mZ\033[0m"
        echo "Not Connected!"
    fi
    clear
    sleep 1
done

Upvotes: 2

Views: 7436

Answers (1)

sigpwned
sigpwned

Reputation: 7453

Your script is not giving output because ping never terminates. To get ping to test your connectivity, you'll want to give it a run count (-c) and a response timeout (-W), and then check its return code:

#!/bin/bash
while true
do
    if ping -c 1 -W 5 google.com 1>/dev/null 2>&1 
    then
        echo "Connected!"
        break
    else
        echo "Not Connected!"
        sleep 1
    fi
done

ping will return 0 if it is able to ping the given hostname successfully, and nonzero otherwise.

It's also worth noting that an iteration of this loop will run for a different period of time depending on whether ping succeeds quickly or fails, for example due to no network connection. You may want to keep the iterations to a constant length of time -- like 15 seconds -- using time and sleep.

Upvotes: 8

Related Questions