Reputation: 137
I need a bash script for checking internet connectivity. I used the below one first.
#!/bin/bash
#
while true; do
if ping -c 1 1.1.1.1 &> /dev/null
then
echo "internet working"
else
echo "no internet"
fi
sleep 5
done
It works fine but fails sometimes. So I was looking for something that would do ping test on multiple IP's, this way only one of the IP has to ping successfully to assume connectivity. I am extremely new to bash, so apologies for any mistakes.
How do I correct the below script so it works as intended?
#!/bin/bash
#
while true; do
count= '0'
if ping -c 1 1.1.1.1 &> /dev/null
then
count= '1'
fi
if ping -c 1 8.8.8.8 &> /dev/null
then
count= count + '1'
fi
if ping -c 1 www.google.com &> /dev/null
then
count= count + '1'
fi
if [ count -lt 1 ]
then
echo "no internet"
else
echo "internet working"
fi
sleep 5
done
Upvotes: 0
Views: 823
Reputation: 10133
I'd use a function for this task, so that I can pass the hosts to be pinged as arguments:
#!/bin/bash
# Check internet connectivity
# Returns true if ping succeeds for any argument. Returns false otherwise
ckintconn () {
for host
do
ping -c1 "$host" && return
done
return 1
} &>/dev/null
if ckintconn 1.1.1.1 8.8.8.8 www.google.com
then
echo "internet working"
else
echo "no internet"
fi
Upvotes: 1
Reputation: 47127
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.
Upvotes: 3