2

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?

Bogdan Timofeev
  • 1,062
  • 3
  • 11
  • 33

2 Answers2

9

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)
chepner
  • 497,756
  • 71
  • 530
  • 681
2

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
Leonardo Pineda
  • 990
  • 8
  • 10