如何获取状态代码,上次重定向URL和CURL命令的输出?

时间:2014-01-07 22:41:05

标签: curl

我正在通过Ruby中的系统调用运行curl命令。

我想要一种方法来获取状态代码,最后重定向的URL,以及我可以轻松解析的漂亮输出中的命令输出。

目前我的命令如下所示: curl -v -s“http://aol.com” - max-redirs 5 --location --connect-timeout 20 -m 20 2>& 1

但是,这给了我太多的信息,我必须解析所有内容以提取状态代码和输出,如下所示:

* 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 -->

3 个答案:

答案 0 :(得分:0)

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

此代码提供上次重定向网址的状态代码。

答案 1 :(得分:0)

我的回答需要两者的结合

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

答案 2 :(得分:-1)

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