What's the exit code for "curl -I" when not HTTP 200?

9,082

Solution 1

curl -I will always return 0, if it managed to produce an output with the HEAD. You have two alternatives.

The first is to use curl -I --fail instead, and check for exit code 22.

If you're doing this in a Python script, it could look like:

try:
    subprocess.check_call(['curl', '-I', '--fail', url])
except subprocess.CalledProcessError as e:
    if e.returncode == 22:
        (do something)

The second is to actually ask just the HTTP status code, like this:

$ curl -s -I -o /dev/null -w '%{http_code}' $bad-url
403

Solution 2

If you truly just want the HTTP status codes from a python script, you may want to check out the 'requests' library:
http://docs.python-requests.org/en/latest/

#Prints status code:    
import requests
r = requests.get('http://superuser.com')
print(r.status_code)
Share:
9,082

Related videos on Youtube

Nemo
Author by

Nemo

Updated on September 18, 2022

Comments

  • Nemo
    Nemo over 1 year

    I want to check what HTTP status code is returned for an HTTP(S) URL. I don't care about content, so I just request head with curl -I $url or curl --head $url

    But what's the exit code I should check for, e.g. in subprocess.check_call? In particular, do I get a non-zero exit code for HTTP 403?

  • Nemo
    Nemo almost 9 years
    True, though the question was about curl only for other reasons.