Shell Script to check internet connection status from Linux

In case you need a shell script that can be used to check your internet connection via console, the following script lines could be your friend. The shell script below will perform a wget connection to google with several tries and then returned the value as online or offline string.

#!/bin/bash

wget -q --tries=10 --timeout=20 --spider http://google.com
if [[ $? -eq 0 ]]; then
        echo "Online"
else
        echo "Offline"
fi

If you are new to Shell script, you can follow these steps to create a simple shell script/program. I assume you are able to use nano (actually you may use any other text editor you like such as vi).

Create a new shell script file called check-internet.sh

nano check.sh

Next, paste those code above to the new file

check internet connection script

Now save the file and exit. CTRL + X is used if you are using nano to edit theĀ file.

Now make the file executable

chmod +x check.sh

Finally run the program

sh check.sh

Output

[root@gateway ~]# sh check.sh
Online
[root@gateway ~]#

 

Admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.