Bash ping script file for checking host availability

I would use this, a simple one-liner:

while ! ping -c1 HOSTNAME &>/dev/null; do echo "Ping Fail - `date`"; done ; echo "Host Found - `date`" ; /root/scripts/test1.sh

Replace HOSTNAME with the host you are trying to ping.


I missed the part about putting it in the background, put that line in a shellscript like so:

#!/bin/sh

while ! ping -c1 $1 &>/dev/null
        do echo "Ping Fail - `date`"
done
echo "Host Found - `date`"
/root/scripts/test1.sh

And to background it you would run it like so:

nohup ./networktest.sh HOSTNAME > /tmp/networktest.out 2>&1 &

Again replace HOSTNAME with the host you are trying to ping. In this approach you are passing the hostname as an argument to the shellscript.

Just as a general warning, if your host stays down, you will have this script continuously pinging in the background until you either kill it or the host is found. So I would keep that in mind when you run this. Because you could end up eating system resources if you forget about this.


By passing the parameters '-c 30' to ping, it will try 30 ping and stop. It will check after if the command succeeds. I think it is best to do a loop that contains one ping and check if this ping succeed. Something like that:

while true;
do
  ping -c1 google.com
  if [ $? -eq 0 ]
  then 
    /root/scripts/test1.sh
    exit 0
  fi
done

If by still running on the foreground, you mean it is still printing on the terminal, you can redirect stdin and stdout to /dev/null .


An old post, but as a suggestion you can use the -w option on ping to avoid the loop. For example,

ping -w 30 -c 1 host

will try for 30 seconds with one ping per second (default ping has 1 second interval between pings) and will exit on the first successful ping.

If you don't need a timeout, I.e. wait for ever, just use a very large value with -w.