Get response body and show HTTP code by curl

Solution 1:

It looks like the content of the response is a single line. You could use two read calls to read two lines:

curl -s -w "\n%{http_code}" 'https://swapi.co/api/people/1/?format=json' | {
    read body
    read code
    echo $code
    jq .name <<< "$body"
}

Solution 2:

Solution with return body and HTTP code at last line:

response=$(curl -s -w "\n%{http_code}" https://swapi.co/api/people/1/?format=json)
response=(${response[@]}) # convert to array
code=${response[-1]} # get last element (last line)
body=${response[@]::${#response[@]}-1} # get all elements except last
name=$(echo $body | jq '.name')
echo $code
echo "name: "$name

But still I would rather do this with two separate variables/streams instead of concatenate response body and HTTP code in one variable.

Solution 3:

Tested on bash4 on Ubuntu 18.04LTS:

IFS=$'\n' read -d "" body code  < <(curl -s -w "\n%{http_code}\n" "${uri}")

This forces the output of curl to be on two lines. The change to IFS makes the linefeed the only field separator and the -d "" forces read to read beyond the line feed, treating the two lines as though they are one. Not the most elegant solution, but a one-liner.