卷曲"写出"特定标题的值

slo*_*osd 19 linux bash shell curl

我目前正在编写一个bash脚本,我正在使用curl.我想要做的是获得响应的一个特定标题.

基本上我希望这个命令工作:

curl -I -w "%{etag}" "server/some/resource"
Run Code Online (Sandbox Code Playgroud)

不幸的是,似乎-w, - write-out选项只有一组它支持的变量,并且不能打印作为响应一部分的任何头.我是否需要自己解析curl输出以获取ETag值,或者是否有办法使curl打印特定标题的值?

显然是类似的东西

curl -sSI "server/some/resource" | grep 'ETag:' | sed -r 's/.*"(.*)".*/\1/'
Run Code Online (Sandbox Code Playgroud)

诀窍,但是卷曲过滤头部会更好.

Lri*_*Lri 16

您可以使用单个sed或awk命令打印特定标头,但HTTP标头使用CRLF行结尾.

curl -sI stackoverflow.com | tr -d '\r' | sed -En 's/^Content-Type: (.*)/\1/p'
Run Code Online (Sandbox Code Playgroud)

使用awk,FS=": "如果值包含空格,则可以添加:

awk 'BEGIN {FS=": "}/^Content-Type/{print $2}'
Run Code Online (Sandbox Code Playgroud)


rud*_*udi 15

为"-w"指定的变量不直接连接到http标头.所以看起来你必须自己"解析"它们:

curl -I "server/some/resource" | grep -Fi etag
Run Code Online (Sandbox Code Playgroud)


mal*_*hal 11

v7.83.0 中的新功能

curl -I -s -o /dev/null -w '%header{etag}' https://example.com/
Run Code Online (Sandbox Code Playgroud)

参考: https: //daniel.haxx.se/blog/2022/03/24/easier-header-picking-with-curl/

  • -I= 仅下载标头。
  • -s= 沉默。
  • -o /dev/null= 将输出重定向到文件,null 表示将其输出为空。
  • -w= 将标头参数写入标准输出。


mro*_*ach 6

其他答案使用该-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 $2}'
18

curl -X GET -sI http://ifconfig.co/json | awk -v FS=": " '/^Content-Length/{print $2}'
302
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在这种情况下,“$2”将包含“\r”字符,这可能会导致意外行为。它可以被修复,但是通过将记录分隔符设置为:`'BEGIN{RS="\r\n";} /^Content-Length/{print $2}'` (2认同)