简体   繁体   English

如何在 CURL shell 脚本中捕获超时/错误?

[英]How to catch timeout/errors in a CURL shell script?

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.我想向 URL 发出 cURL GET 请求,并根据返回的 HTTP 代码决定是否对返回的 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.例如,如果通过 cURL 请求某个 url 的 HTTP 代码是有效的(未超时或错误),则将请求返回的数据保存在我系统的某个位置。

How can I actually 'catch' the returned HTTP code (or timeout) and do the decision based on that?我如何才能真正“捕获”返回的 HTTP 代码(或超时)并据此做出决定?

Execute following as script.sh http://www.google.com/ .作为script.sh http://www.google.com/执行以下操作。
-D - dump headers to file -D - 转储头文件
-o - write response to file -o - 将响应写入文件
-s - be silent -s - 保持沉默
-w - display value of specified variables -w - 显示指定变量的值

#!/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

Use $status and $RESPONSE for further processing.使用$status$RESPONSE进行进一步处理。

if you're trying to store the http response to a variable.如果您尝试将 http 响应存储到变量中。

#!bin/bash

STATUS_RECEIVED=$(curl -s --write-out "%{http_code}\n" $envUrl --output output.txt --silent) ;

echo $STATUS_RECEIVED

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM