如何在 Bash 中测试命令的非零退出状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17456689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:49:59  来源:igfitidea点击:

How do I test for a non-zero exit status of a command in Bash?

bashshellif-statementexit-code

提问by 3cheesewheel

I have a script that checks the exit status of the following function:

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

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

Which returns 0if you're in a git repo, and 128if you're not.

0如果您在 git repo 中,128则返回,如果不在,则返回。

I have no problem testing to see if the return value is 0; the following works as expected:

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

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

But it's when I'm trying to test for an exit status that is anything OTHER than 0when I'm running into problems. I've tried the following, but none of them work:

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

  1. if [[ "$(is_git_repository)" != "0" ]] ; ...always evaluates to true (link)
  2. if [[ "$(is_git_repository)" -ne "0" ]] ; ...always evaluates to false
  3. if [[ "$(is_git_repository)" != 0 ]] ; ...always evaluates to true
  4. if [[ "$(is_git_repository)" -ne 0 ]] ; ...always evaluates to false
  5. if [[ ! "$(is_git_repository)" ]] ; ...always evaluates to true
  6. if !is_git_repository ; ...just echoes the command back to me, but without the bang (wtf?)
  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?)

What is the correct way to check for a non-zero exit status of a command in an if statement?

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

回答by 3cheesewheel

I soon figured out that if ! is_git_repository ; then ...works as intended (look under 7.1.2.1. Testing exit statusin 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.

我很快就发现它if ! is_git_repository ; then ...按预期工作(查看7.1.2.1。if 简介中测试退出状态),但为什么呢?我原以为#1 至少会起作用,但我不知道为什么它不起作用。

Also, what is up with #6?!

还有,#6 怎么了?!

回答by Christoph2

Consider boolean shortcut instead of an ifstatement:

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

is_git_repository || echo you are NOT in a git repo