0

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?

user93726
  • 683
  • 1
  • 9
  • 22
  • Perhaps you have a newline in `$configData`. Can you try to quote your vars: `echo $(validateUpdate "$configData" "$response")` – Walter A Feb 19 '18 at 22:42
  • Post an example of `${result[@]}` – iamauser Feb 19 '18 at 22:43
  • Does this answer your question? [Curl to return http status code along with the response](https://stackoverflow.com/questions/38906626/curl-to-return-http-status-code-along-with-the-response) – hanshenrik Aug 24 '23 at 14:06

2 Answers2

0

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"
tworec
  • 4,409
  • 2
  • 29
  • 34
  • `echo $(command)` is usually better written `command` unless you specifically *require* the shell to perform whitespace tokenization and wildcard expansion on the output from `command` before printing it. See also [useless use of `echo`](http://www.iki.fi/era/unix/award.html#echo) – tripleee Feb 20 '18 at 12:20
0

Use this:

RESPONSE=$(curl --request POST \
  --url $URL \
  -w "\n%{http_code}" \
  -s)


RESPONSE_CODE=$(tail -n1 <<< "$RESPONSE")
RESPONSE_BODY=$(sed '$ d' <<< "$RESPONSE")

echo "Response code = ${RESPONSE_CODE}"
echo "Response body = ${RESPONSE_BODY}"
Shubham Arora
  • 807
  • 9
  • 10