bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Built-in `test -a` returns incorrectly


From: Chet Ramey
Subject: Re: Built-in `test -a` returns incorrectly
Date: Mon, 18 Nov 2024 13:31:32 -0500
User-agent: Mozilla Thunderbird

On 11/18/24 6:31 AM, Klüver, Tibor wrote:

Bash Version: 5.2
Patch Level: 15
Release Status: release

Description:
         Built-in `[ -a ... ]` returns true when false, negation with `!` is 
also very strange.
         `[[` is not affected, neither is `/bin/[`.

`test' uses an algorithm based on the number of arguments supplied. The
man page specifies the precedence and behavior for each number of
arguments.


Repeat-By:
         * touch file
         * [ -a file ] && echo exists         => exists

Two arguments: -a is a unary primary with two arguments, and file exists.

         * [ ! -a file ] && echo exists       => exists

Three arguments: -a is a binary primary, both arguments are non-empty
strings; the test succeeds.

         * [ ! ! -a file ] && echo exists     => (nothing)

Four arguments: the first argument is `!' so this is the negation of
the three argument test; the test fails.

         * [ ! ! ! -a file ] && echo exists   => (nothing)

Five arguments: operator-precedence parsing using the historical test
algorithm. It's basically `not-not-not' -a file, which is the same as
`not' -a file, which fails.

         * [ ! ! ! ! -a file ] && echo exists => exists

Six arguments: operator-precedence parsing again.

Same as previous, just add another `not' at the beginning, so it's
the result of the binary `-a file' test, which succeeds.

This is the reason POSIX recommends not using more than two or three
argument tests and using the shell's && and || operators to compose
more complicated tests.

--
``The lyf so short, the craft so long to lerne.'' - Chaucer
                 ``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/

Attachment: OpenPGP_signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]