如何使用curl to variables保存数据和响应头

如何使用curl to variables保存数据和响应头,curl,sh,Curl,Sh,我有一个带有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执行此操作?使用-D选项将标题写入文件,

我有一个带有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执行此操作?

使用
-D
选项将标题写入文件,然后将其读入变量

data=$(curl -D headers.txt -X GET ...)
headers=$(cat headers.txt)

我建议以下操作打开终端并运行:

~ $ 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"
如果我们想要一个特定的数据,例如内容类型,请执行以下操作

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