Wednesday, June 11, 2014

curl command to error out on HTTP error codes

$ curl -I -f ""
HTTP/1.1 200 OK
Date: Tue, 10 Jun 2014 20:01:02 GMT
Server: Apache

Ah! but it does not provide the / at the tail. We get a 404.

$ curl -I ""
HTTP/1.1 404 Not Found
Date: Tue, 10 Jun 2014 20:01:15 GMT
Server: Apache

echo $? will return 0 in both the case.

What if we are using it inside a script and want the process to fail on non success HTTP status?

Use –f option

$ curl -I -f ""
curl: (22) The requested URL returned error: 404

$ echo $?

The man says:

       -f, --fail
              (HTTP)  Fail  silently (no output at all) on server errors. This is mostly done to better enable scripts etc to better deal with failed attempts. In
              normal cases when a HTTP server fails to deliver a document, it returns an HTML document stating so (which often also describes why and more).  This
              flag will prevent curl from outputting that and return error 22.

              This  method  is  not  fail-safe  and  there  are occasions where non-successful response codes will slip through, especially when authentication is
              involved (response codes 401 and 407).

Note: -I is better option to user than --request HEAD, as --request HEAD request will hang for a while :)

No comments: