A Simple Linux Shell Script To Test Internet Connectivity

If you have been following the Linux shell scripting primer so far, you would have seen that most of the things that go in a shell script are the daily Linux Terminal commands.

Here is a demonstration of one such command :

Let us have a shell script which will ping a specific standard website and let us know if it is reachable or not. In fact you can use this as a basic test to check for internet connectivity.

Shell script named pingsite.sh as below :

[cc lang=”bash”]

#!/bin/sh
# Demonstrated for fun by guys at ihaveapc.com
# Ping a standard website with output suppressed, if ping completes then display success else failure

echo “Checking internet connectivity…”
ping -c 5 www.google.com>>/dev/null

if [ $? -eq  0 ]
then
echo “Able to reach internet, yay!”
else
echo ” Not able to check internet connectivity!”
fi

[/cc]

What the above script does is ping google.com for a count of 5 but suppresses the output by redirecting it to a dummy file which is /dev/null so that it is not displayed on the Terminal.

Make the script executable first :

[cc lang=”bash”]

avp@avp-mint ~/scripts $ chmod a+x pingsite.sh
[/cc]

Here is what the output of the executed script looks like when online :

[cc lang=”bash”]

avp@avp-mint ~/scripts $ ./pingsite.sh
Checking internet connectivity…
Able to reach internet, yay!

[/cc]

Output when offline :

[cc lang=”bash”]

avp@avp-mint ~/scripts $ ./pingsite.sh
Checking internet connectivity…
ping: unknown host www.google.com
Not able to check internet connectivity!

[/cc]

[The simpler version of the above is to simply put the ping command with a standard website in a script and run it, that too will be ok as all you need to know is whether pinging major websites turns ok .]

Isn’t it awesome to automate daily or recurring mundane tasks using such tiny Linux shell scripts ?

Cheers.

4 Comments