简体   繁体   English

Bash-如何获取http响应正文和状态代码?

[英]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. 但是,当我创建一个bash函数并将其作为参数发送时,响应主体在函数中将变为“ HTTP / 1.1” ,如下所示。

echo $(validateUpdate $configData $response)

Code for the function - 功能代码-

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

$2 prints as "HTTP/1.1" $ 2打印为“ 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. 您需要将变量用双引号引起来,以防止bash将其拆分为单独的标记。

Try 尝试

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

or even better (echo is useless as @tripleee points out; furthermore curly braces improves readability): 甚至更好(@tripleee指出,echo没用;大括号可以提高可读性):

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

use same thing inside of your function 在函数中使用相同的东西

echo "$2"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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