bug-bash
[Top][All Lists]
Advanced

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

Re: manpage note? weird strings that appear to be equal but create haywi


From: Chet Ramey
Subject: Re: manpage note? weird strings that appear to be equal but create haywire comparisons?
Date: Wed, 26 Aug 2009 22:54:34 -0400
User-agent: Thunderbird 2.0.0.23 (Macintosh/20090812)

Linda Walsh wrote:

> But then I tested equality on the strings and that's the confusing
> part. I have an idea of what's going on but boy do string compares look
> confused.  They perform same on cygwin
> (bashv=3.2.49(22)-release (i686-pc-cygwin)) and Suse11.1:
> (bashv=3.2.39(1)-release (x86_64-suse-linux-gnu)
> 
> Using the simple form:
>    if <expr> ; then echo = "True" else echo False ; fi
> I get:
>     for c=C:\Windows\System32, and v=C:\Windows\System32

(If you use the assignments above, v is actually assigned
the string C:\\Windows\\System32)

> expr = [[ "$c" = "$v" ]]  : "False"
> expr = [ "$c" = "$v" ]    : "False"
> expr = [[ "$c" != "$v" ]] : "True"
> expr = [ "$c" != "$v" ]   : "True"
> expr = [[ $c = $v ]]      : "True"
> expr = [ $c = $v ]        : "False"
> expr = [[ $c != $v ]]     : "False"
> expr = [ $c != $v ]       : "True"
> 
> Note that [[ and [ return different results when the vars are unquoted.

Yes.  There are two differences.

First, the operands in [[ do not undergo all word expansions.  The
arguments to [, since it's a builtin, do.  That doesn't really matter
to this example, but it's worth noting.

Second, the = and != operators in [[ perform pattern matching (= is
the same as ==).  You have to quote the rhs to force string matching.
In pattern matching, the backslash has a special meaning: it quotes the
next character.  So when $v is unquoted, the pattern matcher treats the
pairs of backslashes in $v as one backslash quoting another, and the
strings match.  When using [, bash does straight string comparison, and
the strings are not identical.

Chet

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




reply via email to

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