如何使用$?并测试以检查功能?

sim*_*ico 7 shell bash exit error-handling

    #!/bin/sh

function checkExit(){
    if test "$?" != "0"; then
      echo Command $1 exited with abnormal status
      exit 1;
    else echo $?
    fi
}

function echoThenRun () { # echo and then run the command
  echo $1
  $1
  ret=$?
  echo $ret
  return $ret
}
file=test_file
echo > $file
echoThenRun "test -f $file"
checkExit $file
echo "all right!"
Run Code Online (Sandbox Code Playgroud)

执行脚本的输出:

$  ~/Downloads/test.sh 
test -f test_file
0
1 # why 1 here??
all right!
Run Code Online (Sandbox Code Playgroud)

amp*_*ine 11

有一种更简单的方法可以说明您正在做的事情。如果使用set -x,脚本将在执行前自动回显每一行。

此外,只要您执行另一个命令,$?就会替换为该命令的退出代码。

如果您打算用它做任何事情而不是快速测试并忘记,您就必须将它备份到一个变量。该[实际上是有它自己的退出代码的程序。

例如:

set -x # make sure the command echos
execute some command...
result="$?"
set +x # undo command echoing
if [ "$result" -ne 0 ]; then
    echo "Your command exited with non-zero status $result"
fi
Run Code Online (Sandbox Code Playgroud)


小智 5

在我看来,该命令test "$?" != "0"最终设置$?1.

该值$?在 的参数中使用testtest设置$?为非零值,因为"0"在词法上等于"0"。使得"!="返回test非零。