How to evaluate http response codes from bash/shell script?
I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.
response=$(curl --write-out '%{http_code}' --silent --output /dev/null servername)
Note, format provided for --write-out should be quoted.As suggested by @ibai, add --head
to make a HEAD only request. This will save time when the retrieval is successful since the page contents won't be transmitted.
curl --write-out "%{http_code}\n" --silent --output /dev/null "$URL"
works. If not, you have to hit return to view the code itself.
I needed to demo something quickly today and came up with this. Thought I would place it here if someone needed something similar to the OP's request.
#!/bin/bashstatus_code=$(curl --write-out %{http_code} --silent --output /dev/null www.bbc.co.uk/news)if [[ "$status_code" -ne 200 ]] ; then echo "Site status changed to $status_code" | mail -s "SITE STATUS CHECKER" "my_email@email.com" -r "STATUS_CHECKER"else exit 0fi
This will send an email alert on every state change from 200, so it's dumb and potentially greedy. To improve this, I would look at looping through several status codes and performing different actions dependant on the result.