Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking host availability by using ping in bash scripts

I want to write a script, that would keep checking if any of the devices in network, that should be online all day long, are really online. I tried to use ping, but

if [ "`ping -c 1 some_ip_here`" ] then   echo 1 else   echo 0 fi 

gives 1 no matter if I enter valid or invalid ip address. How can I check if a specific address (or better any of devices from list of ip addresses) went offline?

like image 423
burtek Avatar asked Aug 08 '13 10:08

burtek


People also ask

How do I ping a host in bash?

To execute this script, open a terminal and type './ping.sh host', where ping.sh is the Bash script and host is the first argument. For example run './ping.sh www.google.com' like shown in Figure 2. The output is shown in Figure 3.

How to Ping host or IP address in bash script?

The script first uses ping command to ping host or IP supplied as an argument. In case that destination is unreachable a mail command will be used to notify system administrator about this event. #!/bin/bash for i in $@ do ping -c 1 $i &> /dev/null if [ $? -ne 0 ]; then echo "`date`: ping failed, $i host is down!" | mail -s "$i host is down!"

How do I ping a website in Linux terminal?

To execute this script, open a terminal and type ‘./ping.sh host’, where ping.sh is the Bash script and host is the first argument. For example run ‘./ping.sh www.google.com’ like shown in Figure 2.

What is the Ping variable in Linux?

The ping variable holds a number, which is the number of word ‘bytes’ returned after ‘ping -c 1 $host’ command is executed. If the value of ping variable is greater than 1 it means that the host has responded to our request, which means the host is alive.

How do I run a pingcheck script?

To execute the pingcheck function, we write ‘pingcheck’ outside the function. The first line of this script is the shebang line, which tells the system what interpreter to use in order to interpret the script. The second line is used to get input from the user and $1 means the first argument.


2 Answers

Ping returns different exit codes depending on the type of error.

ping 256.256.256.256 ; echo $? # 68  ping -c 1 127.0.0.1 ; echo $? # 0  ping -c 1 192.168.1.5 ; echo $? # 2 

0 means host reachable

2 means unreachable

like image 188
StianE Avatar answered Sep 22 '22 14:09

StianE


You don't need the backticks in the if statement. You can use this check

if ping -c 1 some_ip_here &> /dev/null then   echo 1 else   echo 0 fi 

The if command checks the exit code of the following command (the ping). If the exit code is zero (which means that the command exited successfully) the then block will be executed. If it return a non-zero exit code, then the else block will be executed.

like image 34
user000001 Avatar answered Sep 20 '22 14:09

user000001