how to use ping in a script how to use ping in a script bash bash

how to use ping in a script


Use ping's return value:

for C in computers; do  ping -q -c 1 $C && ssh $C 'check something'done

ping will exit with value 0 if that single ping (-c 1) succceeds. On a ping timeout, or if $C cannot be resolved, it will exit with a non-zero value.


Use the -w switch (or -t on FreeBSD and OS X) on the ping command, then inspect the command's return value.

ping -w 1 $cRETVAL=$?if [ $RETVAL -eq 0 ]; then    ssh $c 'check something'fi

You may want to adjust the parameter you pass with -w if the hosts you're connecting to are far away and the latency is higher.

From man ping:

   -w deadline          Specify  a  timeout, in seconds, before ping exits regardless of          how many packets have been sent or received. In this  case  ping          does  not  stop after count packet are sent, it waits either for          deadline expire or until count probes are answered or  for  some          error notification from network.


Not all network environments allow ping to go through (though many do) and not all hosts will answer a ping request. I would recommend not to use ping, but instead set the connect timeout for ssh:

for c in compuers; do  ssh -o ConnectTimeout=2 $c 'check something'done