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

前端 未结 6 1105
半阙折子戏
半阙折子戏 2020-12-12 16:48

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

It should print a \".\" every 10 seconds or so, and wait until the server starts to respond.

相关标签:
6条回答
  • 2020-12-12 17:19

    if you need check if the server is available, cause is restarting or something else, you could try to make an wget to the server and parse the response or the error, if you get a 200 or even a 404 the server is up, you could change the wget timeout with --timeout=seconds, You could set timeout to 10 second and make a loop until the grep over the response have a result.

    i dont know if this is what you are searching or really you need the bash code.

    0 讨论(0)
  • 2020-12-12 17:20

    Interesting puzzle. If you have no access or async api with your client, you can try grepping your tcp sockets like this:

    until grep '***IPV4 ADDRESS OF SERVER IN REVERSE HEX***' /proc/net/tcp
    do
      printf '.'
      sleep 1
    done
    

    But that's a busy wait with 1 sec intervals. You probably want more resolution than that. Also this is global. If another connection is made to that server, your results are invalid.

    0 讨论(0)
  • 2020-12-12 17:21

    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
    
    0 讨论(0)
  • 2020-12-12 17:24

    The use of backticks ` ` is outdated. Use $( ) instead:

    until $(curl --output /dev/null --silent --head --fail http://myhost:myport); do
      printf '.'
      sleep 5
    done
    
    0 讨论(0)
  • 2020-12-12 17:27

    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
    
    0 讨论(0)
  • 2020-12-12 17:38

    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.

    0 讨论(0)
提交回复
热议问题