Search code examples
bashtimeoutsleep

How to wake up from a long sleep in bash and exit when an IP becomes unavailable?


I have a script that uses timeout command to check for the availability of an IP and then if the status is 0 then runs a block of code which blocks ports to prevent incoming traffic. I have shared some of the problematic code below:

timeout 10 bash -c "</dev/tcp/$IP/5060"
        status=$( echo $? )
        if [[ $status == 0 ]] ; then
                echo "Primary DC is available..Proceeding to sleep"
                sleep 600 

The issue is that I want to find a way to exit from the 10 minute sleep if the IP becomes unavailable while in sleep. Is there a way to go in sleep, keep checking for an IPs availability at the same time and exit if it becomes unavailable.


Solution

  • The simplest way IMHO is to not do sleep 600, but instead do 600 sleep 1s or 60 sleep 10s or similar, checking status every time it wakes up, e.g. untested:

    for (( i=1; i<=60; i++ )); do
        if timeout 10 bash -c "</dev/tcp/$IP/5060"; then
            sleep 10
        else
            break
        fi
    done
    

    I expect the extra work involved there means that loop would take longer than 10 minutes to run so you might want to reduce 60 to 50 or some other reduced value or take a timestamp from date before entering the loop to compare against the timestamp inside the loop and break if it gets to 10 mins or similar if it's important to wait close to exactly 10 minutes.