如何检查$?在unix shell脚本中不等于零?

use*_*466 36 unix shell

我有一个脚本,它使用test命令检查$?(最后执行的命令的返回码)是否不等于零.代码如下: -

$? 是最后执行的命令的退出状态.

if (test $? -ne 0)
then
//statements//
fi
Run Code Online (Sandbox Code Playgroud)

但是,这种验证方式对于字符串不起作用,因为get语法错误.请为此建议一个合适的替代方案.

mtk*_*mtk 47

首先将其放入变量中,然后尝试对其进行测试,如下所示

ret=$?
if [ $ret -ne 0 ]; then
        echo "In If"
else
        echo "In Else"
fi
Run Code Online (Sandbox Code Playgroud)

这应该有所帮助.


编辑:如果上述内容未按预期工作,则可能是您没有 $?在正确的位置使用.它必须是您需要捕获返回状态的命令之后的下一行.即使在目标和捕获它的返回状态之间还有任何其他单个命令,您将检索此中间命令的returns_status而不是您期望的那个.


des*_*son 21

自从提出这个问题以来,近四年来我无法相信没有人提到这一点.你真的不需要测试是否$?不是0.shell提供&&,||因此您可以根据该测试的隐式结果轻松进行分支.

例如:

some_command && {
    # executes this block of code,
    # if some_command would result in:  $? -eq 0
} || {
    # executes this block of code,
    # if some_command would result in:  $? -ne 0
}
Run Code Online (Sandbox Code Playgroud)

您可以删除任一分支,具体取决于您的需要.所以如果你只想测试失败(即$? -ne 0):

some_command_returning_nonzero || {
    # executes this block of code when:     $? -ne 0
    # and nothing if the command succeeds:  $? -eq 0
}
Run Code Online (Sandbox Code Playgroud)

但是,您在问题中提供的代码可以正常工作.我很困惑你有语法错误并得出结论$?是一个字符串.最有可能导致语法错误的错误代码未提供问题.这一点尤其明显,因为您声称没有其他人的解决方案也能正常工作.发生这种情况时,您必须重新评估您的假设.

注意:如果大括号内的代码返回错误,上面的代码可能会给出令人困惑的结果.在这种情况下,只需使用if命令,如下所示:

if some_command; then
    # executes this block of code,
    # if some_command would result in:  $? -eq 0
else
    # executes this block of code,
    # if some_command would result in:  $? -ne 0
fi
Run Code Online (Sandbox Code Playgroud)


小智 9

执行脚本后尝试此操作:

if [ $? -ne 0 ];
then
//statements//
fi
Run Code Online (Sandbox Code Playgroud)

希望它有所帮助......干杯!