Can I make cURL fail with an exitCode different than 0 if the HTTP status code is not 200

curlexit codehttp-status-code-500stdout

I was always assuming that when curl got an HTTP 500 response it was returning an exit code that meant failure (!= 0), but that seems to be not the case.

Is there a way I can I make cURL fail with an exitCode different than 0 if the HTTP status code is not 200? I know I can use -w "%{http_code}" but that puts it in STDOUT, not as the exit code (besides, I'm also interested in capturing the output, which I don't want to redirect to a file, but to the screen).

Best Answer

curl --fail does part of what you want:

from man curl:

-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 an 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).

But it blocks output to the screen.