2017-10-20 114 views
0

我有一個超級簡單的bash腳本...如何從可執行bash腳本中的curl獲得正確的響應?

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

我試圖調用REST API和解析響應。

當我執行這個腳本,我得到這個反應,這是不是我想要的......

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

當我直視着我的終端上運行curl命令,我得到這個響應,這是什麼我想...

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" 
} 

有人能指出我錯過了什麼,請:)

回答

0

你需要引用的結果,當你想將其保存到一個變量:

#!/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}" 

如果要保留多行,雙引號是很重要的。

+0

謝謝,只是我需要:) – an0nc0d3r

0

要獲得curl的實際輸出,您可以直接在腳本中使用該命令。或者你可以設置終點在一個變量...

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

這可以告訴你你想要什麼。

+0

感謝您的迴應,我看到你先回答,但其他答案實際上提供了我所需要的,因爲它展示了響應被存儲在一個變量準備被解析,這是什麼我會做。 – an0nc0d3r