为了回显特定的输出,在if语句中检查退出状态的最佳方法是什么?

我想的是:

if [ $? -eq 1 ] 
then
    echo "blah blah blah"
fi

我还遇到的问题是,退出语句是在if语句之前,因为它必须有退出代码。此外,我知道我做错了什么,因为退出显然会退出程序。


当前回答

这可能只在有限的用例集中有用,我特别在需要捕获命令的输出并在退出代码报告出错时将其写入日志文件时使用这种方法。

RESULT=$(my_command_that_might_fail)
if (exit $?) 
then
    echo "everything went fine."    
else
    echo "ERROR: $RESULT" >> my_logfile.txt
fi

其他回答

再补充一下这个有用而详细的答案:

如果必须显式检查退出代码,最好使用算术运算符((…)),往这个方向:

run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }

或者,使用case语句:

run_some_command; ec=$?  # grab the exit code into a variable so that it can
                         # be reused later, without the fear of being overwritten
case $ec in
    0) ;;
    1) printf '%s\n' "Command exited with non-zero"; exit 1;;
    *) do_something_else;;
esac

Bash错误处理相关解答:

在Bash脚本中引发错误

你可以添加这个if语句:

if [ $? -ne 0 ];
then
    echo 'The previous command was not executed successfully';
fi

显式if语句的替代

最低限度:

测试$ ?-eq 0 || echo“发生了不好的事情”

完成:

EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened";
exit $EXITCODE

这可能只在有限的用例集中有用,我特别在需要捕获命令的输出并在退出代码报告出错时将其写入日志文件时使用这种方法。

RESULT=$(my_command_that_might_fail)
if (exit $?) 
then
    echo "everything went fine."    
else
    echo "ERROR: $RESULT" >> my_logfile.txt
fi

为了记录,如果脚本使用set -e(或#!/bin/bash -e),因此不能检查$?直接(因为脚本会在任何返回代码上终止,而不是0),但想要处理特定的代码,@gboffis注释很好:

/some/command || error_code=$?
if [ "${error_code}" -eq 2 ]; then
   ...