Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a loop in bash that is waiting for a webserver to respond?

Tags:

bash

Combining the question with chepner's answer, this worked for me:

until $(curl --output /dev/null --silent --head --fail http://myhost:myport); do
    printf '.'
    sleep 5
done

I wanted to limit the maximum number of attempts. Based on Thomas's accepted answer I made this:

attempt_counter=0
max_attempts=5

until $(curl --output /dev/null --silent --head --fail http://myhost:myport); do
    if [ ${attempt_counter} -eq ${max_attempts} ];then
      echo "Max attempts reached"
      exit 1
    fi

    printf '.'
    attempt_counter=$(($attempt_counter+1))
    sleep 5
done

httping is nice for this. simple, clean, quiet.

while ! httping -qc1 http://myhost:myport ; do sleep 1 ; done

while/until etc is a personal pref.


The use of backticks ` ` is outdated.

Use $( ) instead:

until $(curl --output /dev/null --silent --head --fail http://myhost:myport); do
  printf '.'
  sleep 5
done

printf "Waiting for $HOST:$PORT"
until nc -z $HOST $PORT 2>/dev/null; do
    printf '.'
    sleep 10
done
echo "up!"

I took the idea from here: https://stackoverflow.com/a/34358304/1121497