如何使用Bash解析HTTP标头?

jps*_*ook 5 linux bash curl

我需要从使用curl的网页标题中获取2个值.我已经能够使用以下方法单独获取值:

response1=$(curl -I -s http://www.example.com | grep HTTP/1.1 | awk {'print $2'})
response2=$(curl -I -s http://www.example.com | grep Server: | awk {'print $2'})
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何使用单个curl请求单独grep值,如:

response=$(curl -I -s http://www.example.com)
http_status=$response | grep HTTP/1.1 | awk {'print $2'}
server=$response | grep Server: | awk {'print $2'}
Run Code Online (Sandbox Code Playgroud)

每次尝试都会导致错误消息或空值.我确信这只是一个语法问题.

Syl*_*oux 14

完整bash解决方案 演示如何轻松解析其他标头而无需awk:

shopt -s extglob # Required to trim whitespace; see below

while IFS=':' read key value; do
    # trim whitespace in "value"
    value=${value##+([[:space:]])}; value=${value%%+([[:space:]])}

    case "$key" in
        Server) SERVER="$value"
                ;;
        Content-Type) CT="$value"
                ;;
        HTTP*) read PROTO STATUS MSG <<< "$key{$value:+:$value}"
                ;;
     esac
done < <(curl -sI http://www.google.com)
echo $STATUS
echo $SERVER
echo $CT
Run Code Online (Sandbox Code Playgroud)

生产:

302
GFE/2.0
text/html; charset=UTF-8
Run Code Online (Sandbox Code Playgroud)

根据RFC-2616,HTTP标头的建模如"ARPA Internet文本消息格式标准"(RFC822)中所述,其中明确说明了第3.1.2节:

字段名称必须由可打印的ASCII字符组成(即,值介于33.和126之间的字符,十进制,冒号除外).字段体可以由除CR或LF之外的任何ASCII字符组成.(虽然CR和/或LF可能存在于实际文本中,但它们会通过展开字段的操作被删除.)

所以上面的脚本应该捕获任何RFC- [2] 822兼容的头文件,但折叠头文件有明显的例外.