简体   繁体   中英

Bash - How to get http response body and status code?

I am trying below code to get response body and status:

read -ra result <<< $(curl -i --insecure \
    -H "Accept: application/json" \
    -H "Content-Type:application/json" \
    -X POST --data "$configData" $openingNode"/voice/v1/updateWithPh")
status=${result[1]}
response=${result[@]}
echo $status

Problem here is -

I get both status code and response Body correctly. But when I create a bash function and send it as an argument, the response body changes to "HTTP/1.1" in the function as shown below.

echo $(validateUpdate $configData $response)

Code for the function -

function validateUpdate(){
   echo $1
   echo $2
}

$2 prints as "HTTP/1.1"

What is the reason? How to rectify this issue?

You need to enclose your variables in double quotes to prevent bash splitting it into separate tokens.

Try

echo $(validateUpdate "$configData" "$response")

or even better (echo is useless as @tripleee points out; furthermore curly braces improves readability):

validateUpdate "${configData}" "${response}"

use same thing inside of your function

echo "$2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM