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?
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.
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!"
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 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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With