How can I ping a certain address and when found, stop pinging.
I want to use it in a bash script, so when the host is starting up, the script keeps on pinging and from the moment the host is available, the script continues...
thanks! ;-)
|
How can I ping a certain address and when found, stop pinging. I want to use it in a bash script, so when the host is starting up, the script keeps on pinging and from the moment the host is available, the script continues... thanks! ;-) |
||||
|
|
|
Ping the target host once. Check if the ping succeeded (return value of ping is zero). If host is not alive, ping again. The following code can be saved as a file and called with the hostname as argument, or stripped of the first and last line and used as function within an existing script (waitForHost hostname). The code does not evaluate the cause for failure if the ping does not result in a response, thus looping forever if the host does not exist. My BSD manpage lists the meaning of each return value, while the linux one does not, so I guess this might not be portable, that's why I left it out.
|
|||||||||||||||
|
|
you can do a loop, send one ping and depending on the status break the loop, for example (bash): while true; do ping -c1 www.google.com > /dev/null && break; done putting this somewhere in your script will block, until www.google.com is pingable. m |
|||
|
|
You may remove sleep 1, it's only here to prevent any flooding problem in case where the host would be reacheable but ping would not exit with code 0. |
|||
|
|
|
A further simplification of Martynas' answer:
note that ping itself (negated by |
|||
|
|
|
Please see good options at stackoverflow. Here is a sample in bash, you will have to loop over the following code until it returns a successfull ping result.
|
|||
|
|
|
any of the above loops can also be used with fping rather than ping which, IMO, is better suited for use in scripts than ping itself. see fping(8) for details. while ! fping -q $HOSTNAMES ; do :; done also useful for testing if machines are up before doing something on them. a simple example:
for h in HOST1 HOST2 HOST3 ; do
if fping -q $h ; then
echo -n "$h : "
ssh $h "uname -a"
fi
done
|
|||||
|