Bash的if语句表达式评估为FALSE,但$?为0,为什么?

huangapple go评论55阅读模式
英文:

Bash if statement expression evaluates to FALSE but $? is 0, why?

问题

以下是翻译好的部分:

在下面的示例中,如预期地回显1

test -f /usr/bin
echo "$?" #1

为什么下面的示例回显0

if [[ -f /usr/bin ]]; then
	echo "Inside if statement" # 此行从未执行	
fi
echo "$?" #0

我知道$?评估为上次执行命令的返回值。根据我的理解,最后执行的命令是 test,它是由 if 语句隐式调用的,因为条件评估为假,所以应该返回 1,但当我执行它时,它返回 0。有人能解释为什么这种行为与直接执行 test(就像在第一个示例中)时不同吗?

英文:

The example below echoes 1, as expected:

test -f /usr/bin
echo "$?" #1

Why does the following example echo 0?

if [[ -f /usr/bin ]]; then
	echo "Inside if statement" # This line is never executed	
fi
echo "$?" #0

I know that the $?evaluates to the returned value of the last executed command. In my understanding, the last executed command is test, that is implicitly called by the if statement, since the condition evaluates to false it should return 1, but when I execute it, it returns 0. Can anybody explain why the behavior is different than when test is executed directly (like in the first example)?

答案1

得分: 3

根据 man bash

> * if list; then list; [ elif list; then list; ] ... [ else list; ] fi
>
> 执行 if list。如果其退出状态为零,则执行 then list。否则,依次执行每个 elif list,如果其退出状态为零,则执行相应的 then list 并完成命令。否则,如果有的话,执行 else list。退出状态是最后一个执行的命令的退出状态,如果没有测试条件为真,则为零

英文:

According to man bash:

> * if list; then list; [ elif list; then list; ] ... [ else list; ] fi
>
> The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the
command completes. Otherwise, the else list is executed, if present. The exit status is the exit status
of the last command executed, or zero if no condition tested true.

huangapple
  • 本文由 发表于 2023年6月1日 23:19:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定