Bourne shell short-circuit operators improperly documented

Brett Glass brett at lariat.net
Fri Jul 17 23:18:18 UTC 2009


Everyone:

I'm teaching some new employees UNIX basics, and just ran into the 
following text on the sh(1) man page:

    Short-Circuit List Operators
      ``&&'' and ``||'' are AND-OR list operators.  ``&&'' executes the first
      command, and then executes the second command if the exit status of the
      first command is zero.  ``||'' is similar, but executes the second com-
      mand if the exit status of the first command is nonzero.  ``&&'' and
      ``||'' both have the same priority.

This is exactly backward.

&& is a "short circuit AND." It stops right away and doesn't 
evaluate its second operand if its first operand is 0. Why? Because 
if one operand of an AND operation is 0, we already know the 
result: 0. It can't be otherwise.

Likewise, || is a "short circuit OR." It stops right away and 
doesn't evaluate its second operand if the first operand is 1 (or 
anything nonzero). Why? Because if one operand of an OR operation 
is nonzero, the result can never be 0.

How could this error have persisted in the FreeBSD documentation for so long?

--Brett Glass



More information about the freebsd-chat mailing list