如果 <command>; 是什么意思? [ $? = 4 ];那么<...>呢?

What does if <command>; [ $? = 4 ]; then <...> do?

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

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关键字后面有这样的语句。

谢谢!

让我们回顾一下 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 的状态退出。

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