tzippy
tzippy

Reputation: 6638

Obtain Status Code and Response Body from Curl Request

I want to check http repsonse codes from curl yet still be able to retrieve the returned data and store it in a variable.

I found this answer very helpful: https://superuser.com/a/862395/148175 The user describes how he created a new filedescriptor 3 that redirects to STDOUT .

Then he ran curl in a subshell where he captured the output of -w "%{http_code}" into a variable HTTP_STATUS and the output to the STDOUT with -o >(cat >&3).

My problem is that I want to capture the output of the STDOUT into a variable after I run curl within a function.

This is my script:

#!/bin/bash

exec 3>&1

function curlBinData {
    HTTP_STATUS=$(curl -s -w "%{http_code}" -o >(cat >&3) https://www.google.com --data-binary $1)
    if [ $HTTP_STATUS -ne 200 ]; then
        echo Error: HTTP repsonse is $HTTP_STATUS
        exit
    fi
}

responsedata=$(curlBinData '{"head":5}')
echo $responsedata

What it does:

The output of curl is directed to STDOUTand printed in the console window.

What's desired

Since the function calling curl is run in a subshell, it should direct the output to the variable responsedata.

Upvotes: 2

Views: 14226

Answers (1)

Aidan Lovelace
Aidan Lovelace

Reputation: 418

From what I understand, you want this function to output Error: HTTP repsonse is $status if $status is not equal to 200 and otherwise output the response body, so here is the code for that. I did not see a need for an additional file descriptor, so I removed it.

#!/bin/bash
function curlBinData {
    local res=$(curl -s -w "%{http_code}" https://www.google.com --data-binary $1)
    local body=${res::-3}
    local status=$(printf "%s" "$res" | tail -c 3)
    if [ "$status" -ne "200" ]; then
        echo "Error: HTTP repsonse is $status"
        exit
    fi
    echo $body
}

responsedata=$(curlBinData '{"head":5}')
echo $responsedata

Edit: Simplified the evaluation of the status code from the curl response to just get the last three characters a.k.a. the status code.

Upvotes: 8

Related Questions