2

Objective

Assign HTTP status code and date from cURL output to RESP and DATE variables using one-liner command.

Expectation

[08 Nov 2017 19:28:44 GMT] 301

Reality

$ read -d "\n" RESP DATE <<< $(curl -sv https://google.com 2>&1 | egrep -i "< HTTP/2|< Date" | sed "s/< HTTP\/2 //;s/< date: //g"); echo "[$DATE] $RESP"
[
] 30108 Nov 2017 19:28:44 GMT
$

EDIT:

Here's the full working command:

$ read -d "\r" RESP DATE <<< $(curl -sv https://google.com 2>&1 | tr -d "\r" | egrep -i "< HTTP/2|< Date" | sed "s/< HTTP\/2 //;s/< date: //g"); echo "[$DATE] $RESP"
[Wed, 08 Nov 2017 19:57:33 GMT] 301
$

2 Answers 2

2

The output of curl contains some \r characters, that's why the output looks messed up. You can get rid of it by inserting a tr -d '\r' into the pipeline after the curl and before the egrep.

Is it really important to read into RESP and DATE variables? You could use Awk to extract the interesting parts simpler, saner, and output directly in the desired format:

curl ... | tr -d '\r' | awk '/^< Date: / { date = substr($0, 9); print "[" date "] " resp } /^< HTTP\// { resp = $3 }'
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It works now! I edited my post with full working command. Cheers!
2

How about awk:

curl --silent --head https://google.com | awk '
    /^HTTP/ {code = $2} 
    /^Date:/ {
        sub(/\r$/,"")
        date = substr($0,7)
        printf "[%s] %s\n", date, code
        exit
    }
'

Using an HTTP HEAD request to minimize traffic.

Comments

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.