12

我有一个脚本可以检查以下函数的退出状态:

function is_git_repository {                                                    
    git branch &> /dev/null                                                     
}  

0如果你在一个 git repo 中,它会返回,128如果你不是。

我没有问题测试返回值是否为0; 以下按预期工作:

if is_git_repository ; then 
    echo you are in a git repo
else 
    echo you are NOT in a git repo
fi

但是,当我尝试测试退出状态时,0与遇到问题时不同。我尝试了以下方法,但它们都不起作用:

  1. if [[ "$(is_git_repository)" != "0" ]] ; ...总是评估为真(链接
  2. if [[ "$(is_git_repository)" -ne "0" ]] ; ...总是评估为假
  3. if [[ "$(is_git_repository)" != 0 ]] ; ...总是评估为真
  4. if [[ "$(is_git_repository)" -ne 0 ]] ; ...总是评估为假
  5. if [[ ! "$(is_git_repository)" ]] ; ...总是评估为真
  6. if !is_git_repository ; ...只是将命令回显给我,但没有爆炸(wtf?)

在 if 语句中检查命令的非零退出状态的正确方法是什么?

4

2 回答 2

10

I soon figured out that if ! is_git_repository ; then ... works as intended (look under 7.1.2.1. Testing exit status in Introduction to if), but why? I would have expected that #1 would work at the very least, but I don't know why it doesn't.

Also, what is up with #6?!

于 2013-07-03T19:36:28.753 回答
3

考虑布尔快捷方式而不是if语句:

is_git_repository || echo you are NOT in a git repo
于 2016-11-28T09:44:58.510 回答