How to start Safari on a browser page only when Error 502 stops happening

bashsafariterminal

I've got a situation where if I push an update to an instance on the web, it will take 3-5 minutes to compile, then when that compiling has successfully finished, the instance will shoot Error 502 for a couple of minutes before it will start running again.

I'm looking for a solution where, the instance (a server URL) will be queried every 5 seconds or so, and when it stops replying 502, Safari will boot up.

Any idea how I could do that? So far, on the terminal, I can run this:

curl -I http://url 2>/dev/null | head -n 1 | cut -d$' ' -f2

and this will output the HTTP Port response or whatever, but I'm not savvy enough to "do that every 5 seconds" or to define a "If (resulting response) is X, keep repeating loop, but If (resulting response) is Y, then launch Safari with an URL".

Any ideas?

Best Answer

A "quick and dirty" script to accomplish what you are looking to do could be written as:

#!/bin/bash

url = "http://url"
code=`curl -I $url 2>/dev/null | head -n 1 | cut -d$' ' -f2`

while [ "$code" == 502 ]
do
  sleep 5
  echo trying again
  code=`curl -I $url 2>/dev/null | head -n 1 | cut -d$' ' -f2`
done

open -a Safari $url

Basically, what it does is caputure the value that you output in a variable called code. It then evaluates that variable in a While/Do loop every 5 seconds until the value changes. Once that happens, it exists the loop and launches a Safari instance pointing to the URL.