I have endpoint which returns JSON (response body). I need get by curl the response body and process it (for example using jq). It works:

response=$(curl -s https://swapi.co/api/people/1/?format=json)
name=$(echo $response tmpFile | jq '.name') # irrelevant command, but I need here response body
echo "name:"$name

But I also need show the HTTP Code (to show if the request is succeed):

curl -s -w "%{http_code}\n" -o /dev/null https://swapi.co/api/people/1/?format=json

How get the response body to variable and show HTTP code at the same time (one request)?

I find out solution witch temporary file:

touch tmpFile
curl -s -w "%{http_code}\n" -o tmpFile https://swapi.co/api/people/1/?format=json
name=$(cat tmpFile | jq '.name') # irrelevant command, but I need here only body response
echo "name: "$name
rm tmpFile

How to do without creating file?

I try with named pipe (but it still need to creating file on disk...):

mkfifo tmpFifo
curl -s -w "%{http_code}\n" -o tmpFifo https://swapi.co/api/people/1/?format=json
name=$(cat tmpFifo | jq '.name') # irrelevant command, but I need here only body response
echo "name: "$name
rm tmpFifo

But the named pipe is not removing.

There is solution without creating any file, for example only witch variables or streams?


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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.