Rufen Sie den Antworttext ab und zeigen Sie den HTTP-Code per curl an

7949
mkczyk

Ich habe einen Endpunkt, der JSON (Antworttext) zurückgibt. Ich muss den Antwortkörper durch Locken bekommen und ihn verarbeiten (zum Beispiel mit jq). Es klappt:

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 

Ich brauche aber auch den HTTP-Code (um zu zeigen, ob die Anfrage erfolgreich ist):

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

Wie kann der Antworttext gleichzeitig zu einer Variablen werden und HTTP-Code anzeigen (eine Anforderung)?


Ich finde Lösung mit temporärer Datei heraus:

touch tmpFile curl -s -w "%\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 

Wie mache ich das Erstellen einer Datei?

Ich versuche es mit Named Pipe (aber es muss noch eine Datei auf der Festplatte erstellt werden ...):

mkfifo tmpFifo curl -s -w "%\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 

Aber die Named Pipe wird nicht entfernt.

Es gibt eine Lösung, ohne eine Datei zu erstellen, zum Beispiel nur mit Variablen oder Streams.

3

2 Antworten auf die Frage

2
janos

Es scheint, dass der Inhalt der Antwort eine einzelne Zeile ist. Sie können zwei readAufrufe verwenden, um zwei Zeilen zu lesen:

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

Lösung mit Return Body und HTTP-Code in der letzten Zeile:

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

Trotzdem würde ich dies lieber mit zwei separaten Variablen / Streams tun, anstatt den Antworttext und den HTTP-Code in einer Variablen zu verketten.