how to use ping in a script

Guy picture Guy · Nov 13, 2009 · Viewed 53.3k times · Source

I want a bash script that'll do:

for c in computers:
do
   ping $c
   if ping is sucessfull:
      ssh $c 'check something'
done

If I only do ssh and the computer is iresponsive, it takes forever for the timeout. So I was thinking of using the output of ping to see if the computer is alive or not. How do I do that? Other ideas will be great also

Answer

Stephan202 picture Stephan202 · Nov 13, 2009

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.