在 if bash 语句中检查命令的 return 值

Check return value of command in if bash statement

我有一个简单的脚本,它尝试 curl 和 URL 并在失败或成功时回显一个字符串。但是我收到以下警告,具体取决于我如何形成此 if 语句。

根据我在下面的语句中使用的引号,我收到以下警告:

: -ne: unary operator expected
: integer expression expected

通过替代检查(作为注释),我收到以下错误

((: != 0 : syntax error: operand expected (error token is "!= 0 ")

脚本:

c=`curl -s -m 10 https://example.com` || ce=$?

#if (( ${je} != 0 )); then 
if [ ${ce} -ne 0 ]; then 
        echo "Failed"
else
        echo "Succeeded"
fi

如何在 bash if 语句中正确检查 curl 命令的 return 值?

问题是你只设置了curl命令失败时的退出状态。 如果命令成功,则变量 ce 未设置(也未引用)并且测试执行 if [ -ne 0 ]; then 并打印错误消息。 在这种情况下单独引用变量没有帮助,您只会收到不同的错误消息。

要解决此问题,请在 curl 命令后设置变量 ce,无论 curl 命令的退出状态是什么:

c=$(curl -s -m 10 https://example.com)
ce=$?
if [ "$ce" -ne 0 ]; then 
  echo "Failed"
else
  echo "Succeeded"
fi

或更短,没有退出状态变量:

c=$(curl -s -m 10 https://example.com)
if [ $? -ne 0 ]; then 
  echo "Failed"
else
  echo "Succeeded"
fi