Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question

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.

share|improve this answer

If you just want to display the contents of the curled page, you can do this:

STATUSCODE=$(curl --silent --output /dev/stderr --write-out "%{http_code}" URL)

if test $STATUSCODE -ne 200; then
    # error handling
fi

This writes the page's content to STDERR while writing the HTTP status code to STDOUT, so it can be assigned to the variable STATUSCODE.

share|improve this answer
1  
How about if I want to output the response on failure (non 200), but return a non 0 status code from the script? – Justin May 3 '15 at 23:08
    
@Justin: What about if [ "$statuscode" -ne 200 ]; then exit "$statuscode"; fi ? – ghoti Jun 16 '15 at 14:51
    
@ghoti: Only unsigned 8-bit exit codes are supported, so that could get a little confusing. – Dennis Jun 16 '15 at 16:53
    
Ah, right -- and codes will wrap at 8 bits, so error 404 becomes exit value 148, 500 becomes 244. Confusing indeed! :-) – ghoti Jun 17 '15 at 20:46

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.