How to Check Internet Access Using a Bash Script on Linux

How can I check Internet access using a Bash script on Linux?

Using wget:

#!/bin/bash

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

Linux bash script to check internet connection not working

You don't really need a string comparison here:

ping command gives an appropriate return code after it completes execution.

So, you could use something like:

 function check_connectivity() {

local test_ip
local test_count

test_ip="8.8.8.8"
test_count=1

if ping -c ${test_count} ${test_ip} > /dev/null; then
echo "Have internet connectivity"
else
echo "Do not have connectivity"
fi
}

check_connectivity

Check connection in shell script

You could do the following. Of course, if ping to 8.8.8.8 failed even once, I would say there is an issue somewhere !

status=Failure
for i in 1 2 3 4 5
do
echo Attempt $i
ping -c 1 8.8.8.8
if [ "$?" == "0" ] ; then
status="Success"
fi
done
echo Status of ping test = $status

Creating a shell script to check network connectivity

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 -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

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.

How to check internet connectivity using pinging multiple IP's

Chain the commands in the if statement:

if ping -c 1 1.1.1.1 || ping -c 1 8.8.8.8 || ping -c 1 www.google.com
then
echo "One of the above worked"
else
echo "None of the above worked" >&2
fi

And if needed then you can ofcause still redirect the output of the ping command.

if ping ... > /dev/null # redirect stdout
if ping ... 2> /dev/null # redirect stderr
if ping ... &> /dev/null # redirect both (but not POSIX) `>/dev/null 2>&1` is though.

Bash script for notification when internet is accessible

The correct redirection operator is &>, not 2&>. The 2 is parsed as a separate argument to ping, and since pinging 2 never succeeds, the loop never exists.



Related Topics



Leave a reply



Submit