Wait until a condition becomes true in bash

Viewed 3904

When writing shell scripts, I repeatedly have the need to wait for a given condition to become true, e.g. a remote URL becoming available (checked with curl) or a file that should exist, etc.

Ideally, I'd like to have a function or script await such that I can write, e.g.,

await [[ some condition ]]

and it would check the condition every second until it becomes true or a timeout occurs. Ideally I can set the polling interval and the timeout.

Is there a tool for this out there?

2 Answers

You can use an until loop:

until some condition
do
  sleep 5
done

e.g.

until nc -z localhost 22
do
  echo "SSHd is not up yet. Waiting..."
  sleep 5
done

If you want to add a timeout, you'll have to add that separately with a counter or using the internal SECONDS variable:

SECONDS=0
until nc -z localhost 22
do
  
  if (( SECONDS > 60 ))
  then
     echo "Giving up..."
     exit 1
  fi

  echo "SSHd is not up yet. Waiting..."
  sleep 5
done

I'd use the timeout utility around a while loop that uses sleep.

E.g.:

timeout 1 bash -c 'while :; do echo check; sleep 0.1; done ' 
Related