git 在 zsh 中,如何以程序的退出状态为条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2180328/
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-19 04:04:07  来源:igfitidea点击:

in zsh, how do I do a conditional on the exit status of a program?

gitzshexitstatus

提问by anon

I wnat to do something like:

我想做类似的事情:

if [[ git status &> /dev/null ]]; then
   echo "is a git repo";
else
   echo "is not a git repo";
fi

except I don't know how to do checking on the exit status. How do I fix this?

除了我不知道如何检查退出状态。我该如何解决?

Thanks

谢谢

采纳答案by orip

The variable $?contains the last commands return code

该变量$?包含最后一条命令的返回码

EDIT: precise example:

编辑:精确的例子:

git status &> /dev/null
if [ $? -eq 0 ]; then
  echo "git status exited successfully"
else
  echo "git status exited with error code"
fi

回答by gregseth

Simply like that

就是这样

if git status &> /dev/null
then
   echo "is a git repo";
else
   echo "is not a git repo";
fi

Or in a more compact form:

或者以更紧凑的形式:

git status &> /dev/null && echo "is a git repo" || echo "is not a git repo"

回答by sasquires

Another form that I often use is the following:

我经常使用的另一种形式如下:

git status &> /dev/null
if (( $? )) then
    desired behavior for nonzero exit status
else
    desired behavior for zero exit status
fi

This is slightly more compact than the accepted answer, but it does not require you to put the command on the same line as in gregseth's answer (which is sometimes what you want, but sometimes becomes too hard to read).

这比接受的答案稍微紧凑一些,但它不需要您将命令与 gregseth 的答案放在同一行(有时这是您想要的,但有时变得太难阅读)。

The double parentheses are for mathematical expressions in zsh. (For example, see here.)

双括号用于 zsh 中的数学表达式。(例如,请参见此处。)

Edit: Note that the (( expression ))syntax follows the usual convention of most programming languages, which is that nonzero expressions evaluate as true and zero evaluates as false. The other alternatives ([ expression ], [[ expression ]], if expression, test expression, etc.) follow the usual shell convention, which is that 0 (no error) evaluates as true and nonzero values (errors) evaluate as false. Therefore, if you use this answer, you need to switch the ifand elseclauses from other answers.

编辑:请注意,(( expression ))语法遵循大多数编程语言的通常约定,即非零表达式计算为真,零计算为假。其他选项([ expression ][[ expression ]]if expressiontest expression等)遵循通常的 shell 约定,即 0(无错误)评估为真,非零值(错误)评估为假。因此,如果您使用此答案,则需要从其他答案中切换ifandelse子句。