I am trying to write a bash script in a file that would, when run start pinging a host until it becomes available, when the host becomes reachable it runs a command and stops executing, I tried writing one but the script continues pinging until the count ends,

Plus I need to put that process in the background but if I run the script with the dollar ( $ ) sign it still runs in foreground,

ping -c30 -i3
if [ $? -eq 0 ]
then /root/scripts/test1.sh
exit 0
else echo “fail”
Best Answer

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.


while ! ping -c1 $1 &>/dev/null
        do echo "Ping Fail - `date`"
echo "Host Found - `date`"

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 send the hostname as an argument to the shellscript

Just as a general warning if your host stays down you will have this script ping in the background continuously 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.