How do you write an infinite loop with a timeout, for example waiting for a service?
IntermediateConceptArrays, conditionals and loops
Answer
wait_for_http() { # wait_for_http URL TIMEOUT_SECONDS
local url=$1 deadline=$((SECONDS + $2))
until curl -fsS -o /dev/null --max-time 3 "$url"; do
if (( SECONDS >= deadline )); then
echo "timed out waiting for $url" >&2
return 1
fi
sleep 2
done
}
wait_for_http http://127.0.0.1:8080/readyz 60 || exit 1
Always cap retries with a deadline; an unbounded until loop hangs a deploy forever. The timeout 60 bash -c '...' wrapper is another option.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate