[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Conditional expression problem: both "-a file" and "! -a file" retur
Re: Conditional expression problem: both "-a file" and "! -a file" return true
Sat, 07 Jan 2006 08:17:09 -0700
Mozilla Thunderbird 1.0.2 (Windows/20050317)
-----BEGIN PGP SIGNED MESSAGE-----
According to address@hidden on 1/6/2006 3:02 PM:
> address@hidden:~$ touch testFile
> address@hidden:~$ [ -a testFile ] && echo true || echo false
(http://www.opengroup.org/onlinepubs/009695399/utilities/test.html) that a
test with two arguments (in your case, "-a" and "testFile") produce
unspecified results if the first is neither "!" nor a unary primary. "-a"
is not a required POSIX unary operator. So bash is in its right to return
whatever it wants; in this case, bash has the extension that "-a" is also
a unary operator, returning 0 if file exists (contrast that with
coreutils' /bin/test, which does not have a unary -a, so it currently
returns 1, although it would also be valid for coreutils to print an error
message that an unknown unary operator was encountered and return 2).
> address@hidden:~$ [ ! -a testFile ] && echo true || echo false
Now, in this case, you have three arguments, and POSIX requires that the
binary operator "-a" have higher precedence than the "!" negation operator
on a 2-argument test. And the one-argument test of "!" and of "testFile"
both return true (since neither is the empty string), so the overall
expression returns 0.
You are probably better off using the unary operator -e for file existance
rather than -a. Also, be aware that bash also defines a unary -o, so the
following also has strange results, for the same reasons as above:
$ set -o monitor
$ rm -f monitor
$ test -o monitor && echo true
$ test ! -o monitor && echo true
Life is short - so eat dessert first!
Eric Blake address@hidden
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (Cygwin)
Comment: Public key at home.comcast.net/~ericblake/eblake.gpg
Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org
-----END PGP SIGNATURE-----