[prog] bash: string comparisons in conditionals
riccarda.cassini at gmx.de
Fri Apr 23 13:10:37 EST 2004
Daniel <lc-programming at nada.refused.cc> wrote:
> Well, i've googled a bit and I have to tell, that I was wrong. :)
> I've found a thread where my opinion is also present, but it was
> test x"$var" != "x" && echo '$var' is not empty
> The point is, that the "x" turns the first argument into an ordinary
> word, even when "$var" starts with "-".
this adds another interesting perspective to the issue. Thanks for
doing some further researching! I must admit it didn't occur to me
that a leading dash could be misinterpreted as an option by 'test'.
I guess that's exactly the problem with edge cases: you don't think of
them until they hit you...
Having said this, I'd like to point out that I can't reproduce it,
though. Despite the theoretical appeal of the argument, there doesn't
seem to be a problem in practice. At least not with bash under linux.
I ran a couple of tests with values like '-r' etc., but all tests work
Could this have to do with 'test' being a builtin in bash? I verified
with strace (my new favorite tool, btw, thanks again Almut :-) that no
external call to 'test' takes place. So, I assume that bash is handling
arguments to test/[ internally in a way avoiding any issues with
To get some further insight into this, I ran the same tests with
/bin/sh on some older boxes at work, running under HP-UX 10.20 and
AIX 4.3 (those are the two platforms I hear my colleagues complaining
most loudly about, so I figured they might be appropriate for this...).
In fact, one of the tests fails there, but it's *not* the expected one
[ "$a" = "" ], only the plain 'not'-test [ ! "$a" ]. Same behaviour on
both platforms. (Bad luck for me, I had elected just the !-test to be
my default version to use ;-).
I also wanted to do the same strace analysis to see whether 'test'
actually is being called as an external program by /bin/sh here, but
unfortunately, there doesn't seem to be an strace on those platforms [*].
Btw, if anyone knows whether there are similar debugging tools on those
platforms, I'd like to know... TIA.
Anyway, while reading through the mentioned thread, I felt a little
comforted, as my supposedly trivial original question doesn't seem to
be that simple after all...
[*] actually, on HP-UX there is some strace program, but it seems to be
doing something entirely different. (I did a 'man strace', but what I
got is about the most incomprehensible manpage I've ever encountered so
far - haven't got the faintest idea what they're talking about... ;-)
"Sie haben neue Mails!" - Die GMX Toolbar informiert Sie beim Surfen!
Jetzt aktivieren unter http://www.gmx.net/info
More information about the Programming