【发布时间】:2013-07-03 19:36:28
【问题描述】:
我有一个脚本可以检查以下函数的退出状态:
function is_git_repository {
git branch &> /dev/null
}
如果您在 git repo 中,则返回 0,如果不在,则返回 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 的退出状态时。我已经尝试了以下方法,但它们都不起作用:
-
if [[ "$(is_git_repository)" != "0" ]] ; ...始终评估为真 (link) -
if [[ "$(is_git_repository)" -ne "0" ]] ; ...总是评估为假 -
if [[ "$(is_git_repository)" != 0 ]] ; ...总是评估为真 -
if [[ "$(is_git_repository)" -ne 0 ]] ; ...总是评估为假 -
if [[ ! "$(is_git_repository)" ]] ; ...总是评估为真 -
if !is_git_repository ; ...只是将命令回显给我,但没有爆炸(wtf?)
在 if 语句中检查命令的非零退出状态的正确方法是什么?
【问题讨论】:
-
你似乎在寻找$?
-
您链接到的“来源”既不是该问题的已接受答案,也不是该问题的最高投票答案。
标签: bash shell if-statement exit-code