如何使用 curl 命令从 bash 脚本获取 HTTP 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33300021/
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 I get the HTTP responses from bash script with curl command?
提问by PIppo
I have the following command that I execute from the shell:
我有从 shell 执行的以下命令:
curl -v -s -X GET -H "UserName: myUsername" -H "Password: myPassword"
https://example.com
and from terminal I have the HTTP/1.1 200 response with different response parameters:
从终端我有不同响应参数的 HTTP/1.1 200 响应:
HTTP/1.1 200 OK
Date: Fri, 23 Oct 2015 10:04:02 GMT
Name: myName
Age: myAge
...
Now, in my .sh file i want take name and age so have the values in my variables $name and $age. My initial idea was to redirect stdout to a file to parse:
现在,在我的 .sh 文件中,我想取名字和年龄,所以在我的变量 $name 和 $age 中有值。我最初的想法是将 stdout 重定向到一个文件来解析:
curl -v -s -X GET -H "UserName: myUsername" -H "Password: myPassword"
https://example.com > out.txt
but the file is empty.
但文件是空的。
Some ideas to have a variables in bash script enhanced by the HTTP response?
通过 HTTP 响应增强 bash 脚本中变量的一些想法?
EDIT: the variables that I want to take are in the header of the response
编辑:我想采用的变量在响应的标题中
Thanks
谢谢
回答by Angel O'Sphere
You have to add --write-out '%{http_code}'
to the command line and curl will print the HTTP_CODE to stdout.
您必须添加--write-out '%{http_code}'
到命令行,curl 会将 HTTP_CODE 打印到标准输出。
e.g.curl --silent --show-error --head http://some.url.com --user user:passwd --write-out '%{http_code}'
例如curl --silent --show-error --head http://some.url.com --user user:passwd --write-out '%{http_code}'
However I don't know all the other "variables" you can print out.
但是我不知道您可以打印出的所有其他“变量”。
回答by christophetd
You can make use of the grep and cut command to get what you want.
您可以使用 grep 和 cut 命令来获取您想要的内容。
response=$(curl -i http://yourwebsite.com/xxx.php -H ... 2>/dev/null)
name=$(echo "$response" | grep Name | cut -d ':' -f2)
age=$(echo "$response" | grep MyAge | cut -d ':' -f2)
I changed Ageto MyAge: Age is a standard HTTP header and it is not a good idea to risk to overwrite it.
我将Age更改为MyAge: Age 是标准的 HTTP 标头,冒险覆盖它不是一个好主意。
回答by PIppo
I resolved:
我解决了:
header=$(curl -v -I -s -X GET -H "UserName: myUserName" -H "Password:
myPassword" https://example.com)
name=`echo "$header" | grep name`
name=`echo ${name:4}`
age=`echo "$header" | grep age`
age=`echo ${age:3}`