Henley Wing Chiu
Henley Wing Chiu

Reputation: 22535

How to get Status Code, last redirect URL, and output of CURL command?

I am running a curl command through a system call in Ruby.

I want a way to get the status code, last redirected URL, and output of the command in a pretty output I can easily parse.

Currently my command looks like this: curl -v -s "http://aol.com" --max-redirs 5 --location --connect-timeout 20 -m 20 2>&1

However, this gives me way too much info, and I have to parse everything to extract the status code, and the output as you can see here:

* About to connect() to aol.com port 80 (#0)
*   Trying 198.100.144.135...
* connected
* Connected to aol.com (198.100.144.135) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5
> Host: aol.com
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Tue, 07 Jan 2014 22:31:05 GMT
< Server: Apache/2.2.15 (CentOS)
< X-Powered-By: PHP/5.5.3
< Link: <http://aol.com/?p=290>; rel=shortlink
< Vary: Accept-Encoding,User-Agent
< Connection: close
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
< 
{ [data not shown]
* Closing connection #0
<!doctype html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!-- HTML OUTPUT CONTINUES -->

Upvotes: 0

Views: 2457

Answers (3)

Josh Johanning
Josh Johanning

Reputation: 1245

My answer takes a little from both

site="http://google.com"
status2=`curl -LIs $site | tac | grep -o "^HTTP.*" | cut -f 2 -d' ' | head -1`
if [ "$status2" == "200" ]
then
    echo "website status was - $status2"
    exit
else
    echo "website status was other than '200': was '$status2'"
    exit 1
fi

Upvotes: 0

bitmvr
bitmvr

Reputation: 129

curl -ILs https://your.endpoint.xyz | grep -o "^HTTP.*" | tail -1

Upvotes: 0

swayamraina
swayamraina

Reputation: 3158

status=`curl -ILs $1 | tac | grep -m1 HTTP/1.1 | awk {'print $2'}`;
echo "$status";

This code gives the status code for last redirect URL.

Upvotes: 1

Related Questions