[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Conditional expression problem: both "-a file" and "! -a file" retur
From: |
Eric Blake |
Subject: |
Re: Conditional expression problem: both "-a file" and "! -a file" return true |
Date: |
Sat, 07 Jan 2006 08:17:09 -0700 |
User-agent: |
Mozilla Thunderbird 1.0.2 (Windows/20050317) |
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
According to re2823@Safe-mail.net on 1/6/2006 3:02 PM:
>
> user@machine:~$ touch testFile
> user@machine:~$ [ -a testFile ] && echo true || echo false
> true
POSIX requires
(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).
>
> user@machine:~$ [ ! -a testFile ] && echo true || echo false
> true
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
true
$ test ! -o monitor && echo true
true
- --
Life is short - so eat dessert first!
Eric Blake ebb9@byu.net
-----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
iD8DBQFDv9t084KuGfSFAYARAmpVAJsF+DGBDWhubt2hNB4aVgNMuhTsbgCgliGS
dtP5QKjRVthlW5zcgKcGy00=
=28b8
-----END PGP SIGNATURE-----