Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save both data and response headers with curl to variables

Tags:

curl

sh

I've got a sh script with curl request which saves response to the data variable:

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

But I also need to get one response header value and also save it to variable. How to do this using curl and sh?

like image 833
Bogdan Timofeev Avatar asked Oct 28 '25 10:10

Bogdan Timofeev


2 Answers

Use the -D option to write the headers to a file, then read them into a variable.

data=$(curl -D headers.txt -X GET ...)
headers=$(cat headers.txt)
like image 149
chepner Avatar answered Oct 30 '25 12:10

chepner


I suggest the following open the terminal and run:

~ $ 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"

if we want a specific data for example the Content-Type do the following

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

and we will have

text/html; charset=UTF-8

Now we create a script

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

Add this

#!/bin/bash 

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

echo $result

and now you can execute your script with

~ $ ./script.sh Content-Type
~ $ $PWD/./script.sh Content-Type
~ $ sh $PWD/./script.sh Content-Type
~ $ bash $PWD/./script.sh Content-Type
like image 29
Leonardo Pineda Avatar answered Oct 30 '25 11:10

Leonardo Pineda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!