curl:如果状态为200,如何返回0?

时间:2018-09-14 00:34:29

标签: linux bash shell curl

当响应状态为200时如何返回0?

现在我可以获取状态,例如200,并使用以下命令:

curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s

但是我需要做的就是将此200换成0。

我该如何实现? 我尝试了以下命令,但没有返回

if [$(curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s) == "200"]; then echo 0

4 个答案:

答案 0 :(得分:2)

看起来您需要一些空格和一个fi。这对我有用:

if [ $(curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s) == "200" ]; then echo 0; fi

答案 1 :(得分:2)

您还可以使用-f parameter

  

(HTTP)在服务器错误时静默失败(根本没有输出)。这样做主要是为了更好地使脚本等能够更好地处理失败的尝试。

所以:

curl -f -LI http://google.com

如果呼叫成功,将返回状态0。

答案 2 :(得分:0)

另一种方法是使用布尔运算符&&:

[ $(curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s) == "200" ] && echo 0

仅当第一部分为True时,才会执行第二条命令。

答案 3 :(得分:0)

最简单的方法是检查curl的退出代码。

$ curl --fail -LI http://google.com -o /dev/null -w '%{http_code}\n' -s > /dev/null
$ echo $?
0
$ curl --fail -LI http://g234234oogle.com -o /dev/null -w '%{http_code}\n' -s > /dev/null
$ echo $?
6

请注意,此处--fail是必需的(details in this answer)。还要注意Bob在注释(请参见脚注)中指出的情况,如果代码非200 成功,则仍会返回0

如果您出于某种原因不想使用它,这是另一种方法:

http_code=$(curl -LI http://google.com -o /dev/null -w '%{http_code}\n' -s)
if [ ${http_code} -eq 200 ]; then
    echo 0
fi

您的代码无法正常工作的原因是,您必须在方括号内添加空格。

(摘自我对SuperUser的回答,其中OP交叉张贴了by now deleted问题)