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?
Best Answer
It looks like the content of the response is a single line. You could use two
read
calls to read two lines: