[Top][All Lists]

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

Re: Bug with 'test' built-in.

From: mwoehlke
Subject: Re: Bug with 'test' built-in.
Date: Thu, 10 Aug 2006 10:34:35 -0500
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv: Gecko/20060719 Thunderbird/ Mnenhy/

Paul Jarc wrote:
John Wenker <address@hidden> wrote:
      The following construct _always_ evaluates true, regardless of
      whether the file exists or not.

         if [ ! -a file ]; then
            echo "This line always prints no matter what."
            echo "This line never prints."

-a can act as a prefix unary operator, or an infix binary "and"
operator.  When it appears as the second of three arguments (not
counting "]") in a test, it's treated as a binary operator, even if
the first argument is "!".  So in this case, "!" is test, and as a
single string it's only tested for non-emptiness, and so is considered
true.  Likewise for "file".  Since both subtests are true, the
combined "and" test is also true.

There are a few different ways to get the behavior you want.  You
could use "[ ! \( -a file \) ]" or "! [ -a file ]", although those are
not portable to some other shells.  (The behavior of a test is
generally more predictable when there are fewer arguments, so I'd go
with the second of those two, since it pulls the "!" outside the test
and leaves only two arguments for the test to examine.)  You could
also remove "!" and switch your "then" and "else" clauses, which works
with any shell.

I *know* '! [ -a file ]' is not portable. I tried to use it in some script, somewhere, at some time, and it was sometimes treated as history expansion. Switching clauses may be the only safe way.

vIMprove your life! Now on version 7!

reply via email to

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