我有一个带有curl请求的sh脚本,可以保存对数据变量的响应:
data=$(curl -X GET -H "Authorization: Bearer dee52f918f769f9734599526a296a0d" -H "Accept: application/json" -H "Cache-Control: no-cache" http://someurl.com/data)
但是我还需要获得一个响应头值并将其保存到变量中。 如何使用curl和sh?
这样做答案 0 :(得分:3)
使用-D
选项将标题写入文件,然后将其读入变量。
data=$(curl -D headers.txt -X GET ...)
headers=$(cat headers.txt)
答案 1 :(得分:1)
我建议以下打开终端并运行:
~ $ curl -I https://google.com && echo " Show document info only "
con una salida:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Referrer-Policy: no-referrer
Location: https://www.google.co.ve/?gfe_rd=cr&dcr=0&ei=gIauWsiRGu2FX9_yp6AM
Content-Length: 270
Date: Sun, 18 Mar 2018 15:32:16 GMT
Alt-Svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"
如果我们想要特定数据,例如Content-Type,请执行以下操作
echo $(curl -I https://google.com 2>/dev/null | grep "Content-Type" | head -1 | cut -d":" -f2)
我们将
text/html; charset=UTF-8
现在我们创建一个脚本
~ $ echo '#!/bin/bash'>$PWD'/script.sh' && chmod a+x $PWD'/script.sh'
~ $ echo "open nano to edit the script" && nano $PWD'/script.sh'
添加此
#!/bin/bash
result=$(curl -I https://google.com 2>/dev/null | grep "$@" | head -1 | cut -d":" -f2)
echo $result
现在您可以使用
执行脚本了~ $ ./script.sh Content-Type
~ $ $PWD/./script.sh Content-Type
~ $ sh $PWD/./script.sh Content-Type
~ $ bash $PWD/./script.sh Content-Type