1

I have a super simple bash script...

#!/bin/bash
result=$(curl -i -H "Accept: application/json" -H "Content-Type: application/json" https://jsonplaceholder.typicode.com/posts/1)

I am trying to call a REST API and parse the response.

When I execute this script, I get this response, which is not what I want...

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
146   292  146   292    0     0   1106      0 --:--:-- --:--:-- --:--:--  6790

When I run the curl command directly in my terminal, I get this response, which IS what I want...

HTTP/1.1 200 OK
Date: Fri, 20 Oct 2017 16:07:06 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 292
Connection: keep-alive
Set-Cookie: __cfduid=da76c27cec17567gFH34bd0e2a0ae0ff1508515626; expires=Sat, 20-Oct-18 16:07:06 GMT; path=/; domain=.typicode.com; HttpOnly
X-Powered-By: Express
Vary: Origin, Accept-Encoding
Access-Control-Allow-Credentials: true
Cache-Control: public, max-age=14400
Pragma: no-cache
Expires: Fri, 20 Oct 2017 20:07:06 GMT
X-Content-Type-Options: nosniff
Etag: W/"124-yiKdLzqO5gBghyTrcdJ8Yq0LGnU"
Via: 1.1 vegur
CF-Cache-Status: HIT
Server: cloudflare-nginx
CF-RAY: 3b0d3a6bda04138f-LHR

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

Can someone point out what I'm missing please :)

2 Answers 2

6

You need to quote the result when you want to save it to a variable:

#!/bin/bash
result="$(curl -i -H "Accept: application/json" -H "Content-Type: application/json" https://jsonplaceholder.typicode.com/posts/1)"
echo the result is: "${result}"

The double quotes are important if you want to preserve multiple lines.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, just what I needed :)
0

To get the actual output of curl you can use the command directly in the script. or you can set the endpoint in a variable...

#!/bin/bash
result=https://jsonplaceholder.typicode.com/posts/1
curl  -i -H "Accept: application/json" -H "Content-Type: application/json" $result

This can show you what you want.

1 Comment

Thanks for responding, and I see you answered first but the other answer actually provided me what I needed because it demonstrated the response being stored in a variable ready to be parsed, which is what I will be doing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.