如何在可执行的 bash 脚本中从 curl 获得正确的响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46853407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get correct response from curl in executable bash script?
提问by an0nc0d3r
I have a super simple bash script...
我有一个超级简单的 bash 脚本...
#!/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.
我正在尝试调用 REST API 并解析响应。
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...
当我直接在终端中运行 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"
}
Can someone point out what I'm missing please :)
有人可以指出我缺少什么吗:)
回答by Simone
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.
如果要保留多行,双引号很重要。
回答by Ratul
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...
要获得 curl 的实际输出,您可以直接在脚本中使用该命令。或者您可以在变量中设置端点...
#!/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.
这可以告诉你你想要什么。