bash 卷曲特定标题的“写出”值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12511895/
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
Curl "write out" value of specific header
提问by slosd
I am currently writing a bash script and I'm using curl. What I want to do is get one specific header of a response.
我目前正在编写一个 bash 脚本并且我正在使用 curl。我想要做的是获取响应的一个特定标头。
Basically I want this command to work:
基本上我希望这个命令起作用:
curl -I -w "%{etag}" "server/some/resource"
Unfortunately it seems as if the -w, --write-out option only has a set of variables it supports and can not print any header that is part of the response. Do I need to parse the curl output myself to get the ETag value or is there a way to make curl print the value of a specific header?
不幸的是,似乎 -w, --write-out 选项只有一组它支持的变量,并且无法打印作为响应一部分的任何标头。我需要自己解析 curl 输出来获取 ETag 值还是有办法让 curl 打印特定标题的值?
Obviously something like
显然像
curl -sSI "server/some/resource" | grep 'ETag:' | sed -r 's/.*"(.*)".*//'
does the trick, but it would be nicer to have curl filter the header.
有诀窍,但让 curl 过滤标题会更好。
采纳答案by rudi
The variables specified for "-w" are not directly connected to the http header. So it looks like you have to "parse" them on your own:
为“-w”指定的变量不直接连接到 http 标头。所以看起来你必须自己“解析”它们:
curl -I "server/some/resource" | grep -Fi etag
回答by Lri
You can print a specific header with a single sed or awk command, but HTTP headers use CRLF line endings.
您可以使用单个 sed 或 awk 命令打印特定标头,但 HTTP 标头使用 CRLF 行结尾。
curl -sI stackoverflow.com | tr -d '\r' | sed -En 's/^Content-Type: (.*)//p'
With awk you can add FS=": "if the values contain spaces:
FS=": "如果值包含空格,则可以使用 awk 添加:
awk 'BEGIN {FS=": "}/^Content-Type/{print }'
回答by mroach
The other answers use the -Ioption and parse the output. It's worth noting that -Ichanges the HTTP method to HEAD. (The long opt version of -Iis --head). Depending on the field you're after and the behaviour of the web server, this may be a distinction without a difference. Headers like Content-Lengthmay be different between HEADand GET. Use the -Xoption to force the desired HTTP method and still only see the headers as the response.
其他答案使用该-I选项并解析输出。值得注意的是,-I将 HTTP 方法更改为HEAD. (长选项版本-I是--head)。根据您所追求的领域和 Web 服务器的行为,这可能是没有区别的区别。和Content-Length之间的标题 like可能不同。使用该选项强制使用所需的 HTTP 方法,但仍仅将标头视为响应。HEADGET-X
curl -sI http://ifconfig.co/json | awk -v FS=": " '/^Content-Length/{print }'
18
curl -X GET -sI http://ifconfig.co/json | awk -v FS=": " '/^Content-Length/{print }'
302

