如何使用curl将数据和响应头都保存到变量

Linux文章/教程评论1,141阅读模式

我有一个带有curl request的sh脚本,它将响应保存到data变量:

data=$(curl -X GET -H "Authorization: Bearer dee52f918f769f9734599526a296a0d" -H "Accept: application/json" -H "Cache-Control: no-cache" http://someurl.com/data)

我建议打开终端并运行以下命令:文章源自爱尚资源教程网-https://www.23jcw.net/2589.html

~ $ curl -I https://google.com && echo " Show document info only "

con una salida:文章源自爱尚资源教程网-https://www.23jcw.net/2589.html

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,请执行以下操作文章源自爱尚资源教程网-https://www.23jcw.net/2589.html

echo $(curl -I https://google.com 2>/dev/null | grep "Content-Type" | head -1 | cut -d":" -f2)

我们将会有文章源自爱尚资源教程网-https://www.23jcw.net/2589.html

text/html; charset=UTF-8

现在我们创建一个脚本文章源自爱尚资源教程网-https://www.23jcw.net/2589.html

~ $ echo '#!/bin/bash'>$PWD'/script.sh' && chmod a+x $PWD'/script.sh'
~ $ echo "open nano to edit the script" && nano $PWD'/script.sh'

添加这个文章源自爱尚资源教程网-https://www.23jcw.net/2589.html

#!/bin/bash 
result=$(curl -I https://google.com 2>/dev/null | grep "$@" | head -1 | cut -d":" -f2)
echo $result

现在,您可以使用以下命令执行脚本文章源自爱尚资源教程网-https://www.23jcw.net/2589.html

~ $ ./script.sh Content-Type
~ $ $PWD/./script.sh Content-Type
~ $ sh $PWD/./script.sh Content-Type
~ $ bash $PWD/./script.sh Content-Type
文章源自爱尚资源教程网-https://www.23jcw.net/2589.html文章源自爱尚资源教程网-https://www.23jcw.net/2589.html
相关文章
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
  • 温馨提示:如遇到资源下载不了,或者文章没有解决你的问题的,可以联系我们帮你处理!!!
  • 转载请务必保留本文链接:https://www.23jcw.net/2589.html

发表评论