0

Say I am making a curl request: curl -X HEAD https://example.org -i

i want HTTP Response Code and a header field 'expires' in two different variables without making http request multiple times in my shell script.

Something like this i am currently doing,

url = " -X HEAD https://example.org -i "

httpCode = `eval curl --write-out '%{http_code} ${url}`

expiresHeader = `eval curl ${url} | grep expires`

I want to make only one http request and still be able to get the two fields.

1 Answer 1

1

you can keep the whole response head (status line and headers) in a variable and then "select" only the things you want. for example:

#!/bin/bash

url="https://example.org"

resp=`curl -s --head -i "$url"`
httpCode=`echo "$resp" | head -n 1 | cut -d ' ' -f 2`
expiresHeader=`echo "$resp" | grep "expires"`

echo "$httpCode"
echo "$expiresHeader"

$ bash script
200
expires: Mon, 28 Sep 2020 17:48:41 GMT
$
Sign up to request clarification or add additional context in comments.

2 Comments

It works for me. I was missing 'echo' before running grep on the variable holding the response. Thanks.
@JetinderRathore glad I helped you! if it fixed your problem, please mark it as the accepted answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.