Monday, June 26, 2017

Oracle Linux - bash check for HTTP response code

Bash is one of the most used scripting languages on Linux systems to undertake numerous checks on the system itself and towards other systems. Reason for this, it is available on all Linux hosts and it is very easy to script.

In some cases you might need to be able to know the HTTP status code from a remote HTTP server. A ping command might not do the full trick as it only tells you if the host is responsive to a network ping and getting the whole page might not be a good idea because an error page might be interpreted as a valid response. A better way is to check the HTTP response code that is returned.

In general HTTP resonse codes can be classified as follows:
1xx - informational reponses
2xx - success responses
3xx - redirect responses
4xx - client errors
5xx - server errors

This means that getting a 2xx response will indicate that the server is responding in a good fashion. On all other responses you might want to add some additional actions. Main questions is, how to get only the response code by using a bash script. The below example will do so:

curl -Lw '%{http_code}' -s -o /dev/null -I www.google.com

The above command will return 200 as a response code. In case we would have used a invalid domain name we would have received a error code. The above example is relative simple however will require curl to be present on the system. In case you do not want curl on your system you will have to find an alternative method to execute the check. 
Post a Comment