Bash脚本如何在一个curl调用中提取两个变量中的状态代码和特定头值



假设我正在进行卷曲请求:curl-X HEADhttps://example.org-i

我希望在两个不同的变量中使用HTTP响应代码和一个标头字段"expires",而不会在我的shell脚本中多次发出HTTP请求。

,我目前正在做这样的事情

url = " -X HEAD https://example.org -i "

httpCode = `eval curl --write-out '%{http_code} ${url}`

expiresHeader = `eval curl ${url} | grep expires`

我只想发出一个http请求,并且仍然能够获得这两个字段。

您可以将整个响应头(状态行和头(保存在一个变量中,然后"选择";只有你想要的东西。例如:

#!/bin/bash
url="https://example.org"
resp=`curl -s --head -i "$url"`
httpCode=`echo "$resp" | head -n 1 | cut -d ' ' -f 2`
expiresHeader=`echo "$resp" | grep "expires"`
echo "$httpCode"
echo "$expiresHeader"

$ bash script
200
expires: Mon, 28 Sep 2020 17:48:41 GMT
$

最新更新