linux cURL:如果状态为200,如何返回0?[关闭]

kkih6yb8  于 4个月前  发布在  Linux
关注(0)|答案(4)|浏览(61)

**已关闭。**此问题不符合Stack Overflow guidelines。目前不接受回答。

此问题似乎与a specific programming problem, a software algorithm, or software tools primarily used by programmers无关。如果您认为此问题与another Stack Exchange site的主题相关,可以发表评论,说明在何处可以回答此问题。
三年前就关门了。
这篇文章是编辑并提交审查6个月前,未能重新打开后:
原始关闭原因未解决
Improve this question
当响应状态为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

5cnsuln7

5cnsuln71#

您也可以使用-fparameter
(HTTP)在服务器错误时静默失败(根本没有输出)。这主要是为了更好地使脚本等更好地处理失败的尝试。
于是:

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

字符串
如果调用成功,将返回状态0。

d5vmydt9

d5vmydt92#

看起来你需要一些空格和一个fi。这对我来说很有效:

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

字符串

krcsximq

krcsximq3#

最简单的方法是检查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


你的代码不工作的原因是因为你必须在括号内添加空格。
(复制自我在超级用户(Stack Exchange网站)上的回答,OP在那里交叉发布了by now deleted问题)

i86rm4rw

i86rm4rw4#

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

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

字符串
只有当第一部分为True时,才会执行第二个命令。

相关问题