Knowledge Base

Browse our knowledge base for free solutions to common problems

Wait For Ping Response Then Continue Bash

Created On: 14 September 2022
Written by: Ben

If you are looking to determine the state of a host before actioning something on it then the code snippet below is perfect.

((count = 60))
while [[ $count -ne 0 ]] ; do
    ping -c 127.0.0.1
    rc=$?
    if [[ $rc -eq 0 ]] ; then
        ((count = 1))                   
    else
        sleep 1                          
    fi
    ((count = count - 1))                
done

if [[ $rc -eq 0 ]] ; then           
    echo "The target host is now back online"
    #ANY OTHER ACTIONS IF SUCCESSFUL
else
    echo "The target host failed to respond to ping requests after maximum attempts exceeded."
    #ANY OTHER ACTIONS IF FAILED
fi
ICTU LTD is a company registered England and Wales (Company No. 09344913) 15 Queen Square, Leeds, West Yorkshire, England, LS2 8AJ
Copyright © 2024 ICTU LTD, All Rights Reserved.
exit