为什么shell logical not in if条件测试的行为不符合预期



in my shell:

if ! mycommand;then
  echo "mycommand has 0 exit code"
else
  echo "mycommand has non-zero exit code"
fi

为什么mycommand返回1但回显"mycommand has 0 exit code"?

我将代码修改如下:

mycommand
ret=$?
if [ $ret -eq 0 ]; then
  echo "mycommand has 0 exit code"
else
  echo "mycommand has non-zero exit code"
fi

mycommand返回1时,如我所料,回显"mycommand has non-zero exit code"

只有测试条件返回0,即测试成功,if -block才会执行。非零值将被认为是错误,else块将被执行。

if something; then
    echo "Command succeeded (exit code 0)"
else
    echo "Command failed (exit code $?)"
fi

因此,删除第一个代码块中的!,您将获得所需的行为。

进一步阅读:Bash初学者指南:条件语句

在bash中,0表示true,再高一点表示false。因此,当mycommand为假时,负! mycommand为真。

在shell中,如果执行的命令是正确的,它返回存储在$?中的0。如果我们执行了错误的命令,它返回非零(1-255)值,该值也存储在$?

 Exit Value     Exit Status
 0 (Zero)   Success
 Non-zero   Failure
 1          False
 2          Incorrect usage
 127        Command Not found
 126        Not an executable

最新更新