Reputation: 875
I have the following script:
#!/bin/bash
servers=( "10.10.10.1" "10.10.10.2" "10.10.10.3" "10.10.10.4" )
for i in "${servers[@]}";
do
ping -c 4 "$i" >/dev/null 2>&1 &&
echo "Ping Status of $i : Success" ||
echo "Ping Status of $i : Failed"
done
which outputs
Ping Status of 10.10.10.1 : Success
Ping Status of 10.10.10.2 : Success
Ping Status of 10.10.10.3 : Failed
Ping Status of 10.10.10.4 : Failed
I need to constantly ping those addresses until they all succeed then, execute a command. I don't need the success/failed output, I just want to ping all IPs and then echo "All Hosts Online", for example.
Upvotes: 0
Views: 521
Reputation: 27822
I hope the comments in the code make it clear what this does. Basically, the trick is to wrap the entire thing in an infinite while
loop, and use a variable to signal whether one of the commands failed.
#!/bin/bash
servers=( "10.10.10.1" "10.10.10.2" "10.10.10.3" "10.10.10.4" )
# Keep looping forever : is a special builtin command that does
# nothing and always exits with code 0
while :; do
# Assume success
failed=0
# Loop over all the servers
for i in "${servers[@]}"; do
# We failed one!
if ! ping -c 4 "$i" >/dev/null 2>&1; then
# Set failed to 1 to signal the code after the for loop that
# a ping failed
failed=1
# We don't need to ping the others, so we can break from this for
# loop
break
fi
done
# If none of the ping commands failed, the $failed variable is still 0
if [ $failed -eq 0 ]; then
# Yes! We can now run our command
echo "All hosts online"
# And break the infinite while loop
break
else
# Nope, wait a while and start the loop from the top
sleep 5
fi
done
I also fixed a typo; you used /dev/nul
, but that should be /dev/null
, with two l
.
Upvotes: 1