Kai
Kai

Reputation: 376

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

I stumbled upon this snippet of code and asked myself about it's significance:

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

What irritates me is the [ $? = 4 ] part. It looks like a test for the exit code of the last command which would make sense since "#do a thing" and "#do the other thing" relate to how to deal with different versions of getopt, but is it even evaluated? If so, how? I have never seen such a statement after the if keyword.

Thanks!

Upvotes: 1

Views: 107

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295291

Let's review the output of 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.

In light of the above, consider the following:

  • if COMMANDS; then ... notably accepts COMMANDS -- a list, which can consist of multiple commands combined by separators.
  • foo; bar is a command list which runs both foo and bar; when it's complete, the exit status of the compound command is that of bar.
  • [ $? = 4 ] tests whether the immediately preceding program's exit status is exactly 4.
  • getopt -T >/dev/null 2>&1; [ $? = 4 ] thus tests whether getopt -T exits with a status of precisely 4.

Thus, your code runs the #do a thing block if getopt -T fails with exit status 4, and #do the other thing otherwise.

Upvotes: 2

Related Questions