bash 如何在 CURL shell 脚本中捕获超时/错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18258804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch timeout/errors in a CURL shell script?
提问by Ron
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 代码(或超时)并基于此做出决定?
回答by Sithsu
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
执行如下script.sh http://www.google.com/
。-D
- 将标头转储到文件-o
- 将响应写入文件-s
- 保持沉默-w
- 显示指定变量的值
#!/bin/bash
RESPONSE=response.txt
HEADERS=headers.txt
status=$(curl -s -w %{http_code} -o $RESPONSE)
# or
#curl -s -D $HEADERS -o $RESPONSE
#status=$(cat $HEADERS | head -n 1 | awk '{print }')
echo $status
Use $status
and $RESPONSE
for further processing.
使用$status
并$RESPONSE
进行进一步的处理。