-2

I want to check the ping replies on two IP addresses and if they are both up, then I execute a command.

For example:

ping 8.8.8.8 on response do
ping 8.8.4.4 on response 
execute command

Is there a simple bash script to do this?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Lurch
  • 819
  • 3
  • 18
  • 30

3 Answers3

2

According to the manpage on ping:

If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not.

Thus you can rely on the exit code to determine whether to continue in your script.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1
ping 8.8.8.8 -c 1
if [ $? = 0 ]
then
  echo ok
else
  echo ng
fi

Try ping only 1 time with -c 1 option. Change to any number as you like.

$? is the exit code of the previous command. You can refer ping's exit code with it.

Modify the above code snippet to what you want.

ka_
  • 29
  • 4
  • 2
    It's simpler to just use the `ping` command directly in the `if` statement than to use `test`: `if ping -c 1 8.8.8.8; then`. – chepner Dec 09 '13 at 17:25
0

Bash commands to return yes or no if a host is up.

Try hitting a site that doesn't exist:

eric@dev ~ $ ping -c 1 does_not_exist.com > /dev/null 2>&1; echo $?
2

Try hitting a site that does exist:

eric@dev /var/www/sandbox/eric $ ping -c 1 google.com > /dev/null 2>&1; echo $?
0

If it returns 0, then the host is evaluated to be responsive. If anything other than zero, then it was determined that the host is unreachable or down.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335