如果是的话 ; [$? = 4];然后做?

问题描述 投票:1回答:1

我偶然发现了这段代码并问自己这个代码的重要性:

if `getopt -T >/dev/null 2>&1` ; [ $? = 4 ]
then
#do a thing 
else
#do the other thing
fi

令我恼火的是[$? = 4]部分。它看起来像是对最后一个命令的退出代码的测试,因为“#do a thing”和“#do the other thing”与如何处理不同版本的getopt有关,但它是否甚至被评估?如果是这样,怎么样?我从未在if关键字之后看过这样的语句。

谢谢!

bash if-statement conditional
1个回答
2
投票

让我们回顾一下help if的输出:

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

鉴于上述情况,请考虑以下因素:

  • if COMMANDS; then ...特别接受COMMANDS - 一个列表,它可以由分隔符组合的多个命令组成。
  • foo; bar是一个命令列表,运行foobar;当它完成时,复合命令的退出状态是bar的退出状态。
  • [ $? = 4 ]测试前一个程序的退出状态是否正好是4。
  • 因此,getopt -T >/dev/null 2>&1; [ $? = 4 ]测试getopt -T是否以4的状态退出。

因此,如果#do a thing以退出状态4失败,则代码运行getopt -T块,否则运行#do the other thing

© www.soinside.com 2019 - 2024. All rights reserved.