Shell Script – Retrieve HTTP Status Code and Content from Curl

curlshell-script

I want a script to curl to a file and to put the status code into a variable (or, at least enable me to test the status code)

I can see I can do it in two calls with e.g.

url=https://www.gitignore.io/api/nonexistentlanguage
x=$(curl -sI $url | grep HTTP | grep -oe '\d\d\d')
if [[ $x != 200  ]] ; then
  echo "$url SAID $x" ; return
fi
curl $url # etc ...

but presumably there's a way to avoid the redundant extra call?

$? doesn't help: status code 404 still gets an return code of 0

Best Answer

#!/bin/bash

URL="https://www.gitignore.io/api/nonexistentlanguage"

response=$(curl -s -w "%{http_code}" $URL)

http_code=$(tail -n1 <<< "$response")  # get the last line
content=$(sed '$ d' <<< "$response")   # get all but the last line which contains the status code

echo "$http_code"
echo "$content"

(There are other ways like --write-out to a temporary file. But my example does not need to touch the disk to write any temporary file and remembering to delete it; everything is done in RAM)

Related Question