Get both the headers and the response body in two separate variables?

I'm looking for a way to make an ONE curl call and get variables from it: one with headers and the other with the response body.

I found a few questions about how to separate the headers from the body, but people seem to be interested in only one of them. I need both headers and body.

I cannot use an external file to store the body (while using -o $ file is not an option).

I can use

headers=$(curl -D /dev/stdout $URL) 

to get the headers in one variable, but how can I redirect the output to another variable?

Thanks a lot!

+6
source share
2 answers
 head=true while IFS= read -r line; do if $head; then if [[ -z $line ]]; then head=false else headers+=("$line") fi else body+=("$line") fi done < <(curl -sD - "$url" | sed 's/\r$//') printf "%s\n" "${headers[@]}" echo === printf "%s\n" "${body[@]}" 

To combine array elements into one scalar variable:

 the_body=$( IFS=$'\n'; echo "$body[*]" ) 

In bash 4.3, you can use named links to simplify the transition from header mode to body mode:

 declare -n section=headers while IFS= read -r line; do if [[ $line = $'\r' ]]; then declare -n section=body fi section+=("$line") done < <(curl -sD - "$url") 

For some reason, Glenn Jackman's answer did not catch part of the body of the answer. I had to split the curl request into another command extension and then enclose it in double quotes. Then I did not use arrays, but simply merged values ​​with variables. This works for me:

 output=$(curl -si -d "" --request POST https://$url) head=true while read -r line; do if $head; then if [[ $line = $'\r' ]]; then head=false else header="$header"$'\n'"$line" fi else body="$body"$'\n'"$line" fi done < <(echo "$output") 

Thanks Glenn!

+7
source

I would like to share a way to parse the twist without any external program, bash.

First, get the scroll request response -sw "%{http_code}" .

 res=$(curl -sw "%{http_code}" $url) 

The result will be a string containing the body, followed by the http code.

Then enter the http code:

 http_code="${res:${#res}-3}" 

And the body:

 if [ ${#res} -eq 3 ]; then body="" else body="${res:0:${#res}-3}" fi 

Note that if the length of http_code and response is (length 3), the body is empty. Alternatively, just split the http code and get the body.

+7
source

Source: https://habr.com/ru/post/975304/


All Articles