Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Curl - Get status code and response body
URL="http://stackoverflow.com/"
# store the whole response with the status at the and
HTTP_RESPONSE=$(curl --silent --write-out "HTTPSTATUS:%{http_code}" -X POST $URL)
# extract the body
HTTP_BODY=$(echo $HTTP_RESPONSE | sed -e 's/HTTPSTATUS\:.*//g')
# extract the status
HTTP_STATUS=$(echo $HTTP_RESPONSE | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')
# print the body
echo "$HTTP_BODY"
# example using the status
if [ ! $HTTP_STATUS -eq 200 ]; then
echo "Error [HTTP status: $HTTP_STATUS]"
exit 1
fi
@chbi

This comment has been minimized.

Copy link

chbi commented Mar 1, 2018

one should use quotes in the echo in order to avoid loose of linebreaks

HTTP_BODY=$(echo` "$HTTP_RESPONSE" | sed -e 's/HTTPSTATUS:.*//g')

@Levivb

This comment has been minimized.

Copy link

Levivb commented Nov 5, 2018

The snippet above is pretty nice. However, it doesn't take any occurences of HTTPSTATUS in the response body into account.

The following has a more strict regex to extract the body and status code which will work even with HTTPSTATUS in the response body:

HTTP_BODY=$(echo $HTTP_RESPONSE | sed -E 's/HTTPSTATUS\:[0-9]{3}$//')
HTTP_STATUS=$(echo $HTTP_RESPONSE | tr -d '\n' | sed -E 's/.*HTTPSTATUS:([0-9]{3})$/\1/')

I couldn't get the \d meta sequence to work in the few seconds I put effort in it, so it's just [0-9] instead of \d for now

@archigarg

This comment has been minimized.

Copy link

archigarg commented Aug 16, 2019

Hi, here we have been able to get the "HTTP status code" and the "response body". Is it also possible to get the "HTTP Header values" using $HTTP_RESPONSE?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.