bash 如何检查 curl 是否成功并打印消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38905489/
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 check if curl was successful and print a message?
提问by Aditya Chouhan
I am trying to do a CURL with an IF Else condition. On success of the call Print a successful message or else Print the call failed.
我正在尝试使用 IF Else 条件执行 CURL。呼叫成功时打印一条成功的消息,否则打印呼叫失败。
My Sample Curl would look like:
我的示例卷曲看起来像:
curl 'https://xxxx:[email protected]/xl_template.get_web_query?id=1035066' > HTML_Output.html
I want to do the same thing using Shell.
我想使用 Shell 做同样的事情。
Using JavaScript:
使用 JavaScript:
if(res.status === 200){console.log("Yes!! The request was successful")}
else {console.log("CURL Failed")}
Also, I see the CURL percentage, but I do not know, how to check the percentage of CURL. Please help.
另外,我看到了 CURL 百分比,但我不知道如何检查 CURL 的百分比。请帮忙。
回答by Balaji Reddy
One way of achieving this like,
实现这一目标的一种方法,例如,
HTTPS_URL="https://xxxx:[email protected]/xl_template.get_web_query?id=1035066"
CURL_CMD="curl -w httpcode=%{http_code}"
# -m, --max-time <seconds> FOR curl operation
CURL_MAX_CONNECTION_TIMEOUT="-m 100"
# perform curl operation
CURL_RETURN_CODE=0
CURL_OUTPUT=`${CURL_CMD} ${CURL_MAX_CONNECTION_TIMEOUT} ${HTTPS_URL} 2> /dev/null` || CURL_RETURN_CODE=$?
if [ ${CURL_RETURN_CODE} -ne 0 ]; then
echo "Curl connection failed with return code - ${CURL_RETURN_CODE}"
else
echo "Curl connection success"
# Check http code for curl operation/response in CURL_OUTPUT
httpCode=$(echo "${CURL_OUTPUT}" | sed -e 's/.*\httpcode=//')
if [ ${httpCode} -ne 200 ]; then
echo "Curl operation/command failed due to server return code - ${httpCode}"
fi
fi
回答by heemayl
You can use the -w
(--write-out
) option of curl to print the HTTP code:
您可以使用curl的-w
( --write-out
) 选项打印 HTTP 代码:
curl -s -w '%{http_code}\n' 'https://xxxx:[email protected]/xl_template.get_web_query?id=1035066'
It will show the HTTP code the site returns.
它将显示站点返回的 HTTP 代码。
Also curl
provides a whole bunch of exit codes for various scenarios, check man curl
.
还curl
为各种场景提供了一大堆退出代码,请检查man curl
.
回答by Barmar
Like most programs, curl
returns a non-zero exit status if it gets an error, so you can test it with if
.
与大多数程序一样,curl
如果出现错误,则返回非零退出状态,因此您可以使用if
.
if curl 'https://xxxx:[email protected]/xl_template.get_web_query?id=1035066' > HTML_Output
then echo "Request was successful"
else echo "CURL Failed"
fi
I don't know of a way to find out the percentage if the download fails in the middle.
如果下载在中间失败,我不知道有什么方法可以找出百分比。