Sh-test, bug or not?

Matthew Seaman matthew at FreeBSD.org
Fri Jan 15 08:09:52 UTC 2016


On 15/01/2016 04:32, CK wrote:
> If you have authoritative knowledge on the subject,
> please state if this functionality is correct:
> 
> $ [ ! "" -a "" ] && echo pass || echo fail
> pass
> $ [ ! 11 -a "" ] && echo pass || echo fail
> pass
> 
> The "-a" operator binds stronger than the "!" operator.
> Intuition based on functionality in awk/C would suppose
> that the "!" operator would bind stronger than the "-a"
> operator, especially since "-a" does in fact have higher
> precedence than the "-o" operator, as in awk/C.
> 
> In order to make it work as "expected", it gets ugly:
> 
> $ [ ! "" -a "" ] && echo pass || echo fail
> pass
> $ [ \( ! "" \) -a "" ] && echo pass || echo fail
> fail
> 
> $ [ ! 11 -a "" ] && echo pass || echo fail
> pass
> $ [ \( ! 11 \) -a "" ] && echo pass || echo fail
> fail
> 
> I never noticed this in 20 years, so I don't know if it always
> worked this way, or if something changed in my upgrade from
> 4.11 to 9.3.

I think that while unexpected in comparison to other languages which
have inherited C-like operator precedence rules, this is according to
the POSIX standard for test(1).  As the man page says:

     The test grammar is inherently ambiguous.  In order to assure a
degree of
     consistency, the cases described in the IEEE Std 1003.2 (``POSIX.2''),
     section D11.2/4.62.4, standard are evaluated consistently according to
     the rules specified in the standards document.  All other cases are
sub-
     ject to the ambiguity in the command semantics.

and it notes that the ambiguous cases are those involving (), -a and -o.

Your test might be more clearly expressed as:

$ [ ! "" ] && [ "" ] && echo pass || echo fail
fail

(although I'd recommend the -z and -n operators for testing the
emptiness / undefinedness or not of strings.)

	Cheers,

	Matthew

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 957 bytes
Desc: OpenPGP digital signature
URL: <http://lists.freebsd.org/pipermail/freebsd-questions/attachments/20160115/07cbf5ac/attachment.sig>


More information about the freebsd-questions mailing list