devxvda1
devxvda1

Reputation: 462

Bash multiple variable assignment

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
$

Upvotes: 2

Views: 958

Answers (2)

glenn jackman
glenn jackman

Reputation: 247162

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.

Upvotes: 2

janos
janos

Reputation: 124804

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 }'

Upvotes: 2

Related Questions