如何在shell中建立if条件以检查curl是否成功? [英] How to build an if condition in shell to check whether curl succeeded?

查看:2317
本文介绍了如何在shell中建立if条件以检查curl是否成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Linux中运行返回200的cURL命令.

I am running a cURL command in Linux that is returning 200.

curl -sL -w "%{http_code}" "http://google.com" -o /dev/null

但是,如果我按以下方式运行,则输出为"Fail":

However, If I run the same as below, I get "Fail" as output:

if [ "curl -sL -w "%{http_code}" "http://google.com" -o /dev/null" == "200" ]; then echo "Success"; else echo "Fail"; fi

请让我知道这是怎么回事?

Please let me know that what is wrong here?

推荐答案

您没有正确使用命令替换.用这种方式重写它:

You are not using command substitution correctly. Rewrite it this way:

if [ "$(curl -sL -w '%{http_code}' http://google.com -o /dev/null)" = "200" ]; then
    echo "Success"
else
    echo "Fail"
fi

正如Charles所建议的,只要您要查找成功或失败,就可以使用--fail选项进一步简化此操作:

As Charles suggested, you can further simplify this with --fail option, as long as you are looking for a success or failure:

if curl -sL --fail http://google.com -o /dev/null; then
    echo "Success"
else
    echo "Fail"
fi

这篇关于如何在shell中建立if条件以检查curl是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆