如何在CURL Shell脚本中捕获超时/错误? [英] How to catch timeout/errors in a CURL shell script?

查看:934
本文介绍了如何在CURL Shell脚本中捕获超时/错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向URL发出cURL GET请求,并根据返回的HTTP代码确定是否对返回的HTTP数据进行处理。

I want to issue a cURL GET request to a URL and based on the return HTTP code decide whether to do something with the returned HTTP data.

例如,如果通过cURL进行的某个url请求的HTTP代码有效(没有超时或错误),则将请求返回的数据保存在我的系统中。

For example, if the HTTP code for a certain url request through cURL is valid (not timed out or error), then keep the returned data from the request somewhere in my system.

如何我可以实际捕获返回的HTTP代码(或超时)并基于此做出决定吗?

How can I actually 'catch' the returned HTTP code (or timeout) and do the decision based on that?

推荐答案

执行以下命令 script.sh http://www.google.com/

-D -将标头转储到文件

-o -将响应写入文件

-s -保持沉默

-w -显示指定变量的值

Execute following as script.sh http://www.google.com/.
-D - dump headers to file
-o - write response to file
-s - be silent
-w - display value of specified variables

#!/bin/bash

RESPONSE=response.txt
HEADERS=headers.txt

status=$(curl -s -w %{http_code} $1 -o $RESPONSE)

# or
#curl -s -D $HEADERS $1 -o $RESPONSE
#status=$(cat $HEADERS | head -n 1 | awk '{print $2}')

echo $status

使用 $ status $ RESPONSE 进行进一步处理。

Use $status and $RESPONSE for further processing.

这篇关于如何在CURL Shell脚本中捕获超时/错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆