何时是“[$(命令)]”相当于“如果命令;然后..."? [英] When is "[ $(command) ]" equivalent to "if command; then..."?
问题描述
我回答问题并认为
if [ $(command) ]; then ...
总是相当于
if command; then ...
然而,我得到了几个反例:
$ [ $(true) ] && echo "yes" || echo "no"
no
$ if true; then echo "yes"; else echo "no"; fi
yes
并且:
$ if echo "$xxxx"; then echo "yes"; else echo "no"; fi
yes
$ [ $(echo "$xxx") ] && echo "yes" || echo "no"
no
在这两种情况下,问题出在 true
和 echo $ xxxx
(未设置变量)不返回任何内容,因此 []
评估为False(按照定义在 man test
),而 echo $ xxxx
成功,因此其返回码为0,因此如果
条件评估为真。
In both cases the problem lies in true
and echo $xxxx
(unset variable) do not return anything, so [ ]
evaluates to False (by definition in man test
), whereas echo $xxxx
is successful so its return code is 0 and, therefore, the if
condition evaluates to True.
但是,我想知道:我们什么时候可以假设两个检查都是等价的?在大多数情况下,这是假设的还是可靠的?
However, I wonder: when can we assume both checks are equivalent? Is this a risky thing to assume or it is reliable in most of the cases?
推荐答案
这两个陈述完全不同。当你写
The two statements are totally different. When you write
if command; then ...
您正在测试命令的退出代码。如果为零,则执行该块。另一方面,当你写
you are testing the exit code of command. If it is zero, the block will be executed. On the other hand, when you write
if [ $(command) ]; then ...
您实际上是在测试命令的输出,而不是退出代码。
you are actually testing if the output of the command, and not the exit code.
您链接的示例之所以有效,是因为grep仅在找到匹配项时才会打印到标准输出。
The reason the example you linked works, is because grep only prints to the standard output if it finds a match.
这篇关于何时是“[$(命令)]”相当于“如果命令;然后..."?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!