Re: RFE: allow double quotes to group multi-words & be treated as 1 arg,
From:
Greg Wooledge
Subject:
Re: RFE: allow double quotes to group multi-words & be treated as 1 arg, w/DQ's stripped off -- including RH =~
Date:
Wed, 4 Aug 2010 08:31:57 -0400
User-agent:
Mutt/1.4.2.3i
On Wed, Aug 04, 2010 at 02:02:39AM -0700, Linda Walsh wrote:
> Other string operators? What other ones operate this way?
>
> This is what I'm referring to:
>
> a="hi"
> if [[ "hi" == "$a" ]]; then echo "this matches"; fi
> if [[ 'hi' == '$a' ]] then echo "this doesn't"; fi
You are misunderstanding the role of quotes. Double quotes and single
quotes have some things in common:
* They cause the content inside of them to be treated as a single word,
instead of potentially multiple words.
* They cause shell/pattern metacharacters such as space, asterisk,
parentheses, braces, brackets, etc. to be treated as literal.
And one thing different:
* Double quotes permit `...` and $ substitutions to occur. Single do not.
In your examples, '$a' is matched as the literal string "dollar-sign a".
"$a" is matched as a *string* (not a pattern) whose value is the content
of the variable a.
The example you did NOT show is:
if [[ "hi" == $a ]]; then ...
In that one, the $a is matched as a *pattern* (not a string) whose value
is the content of the variable a. That is the significance of the double
quotes, or their lack.
In action:
imadev:~$ a='*a'
imadev:~$ if [[ "baa" = "$a" ]]; then echo yes; else echo no; fi
no
imadev:~$ if [[ "baa" = $a ]]; then echo yes; else echo no; fi
yes
> I would prefer this work:
>
> a="h."
>
> if [[ "hi" =~ "$a" ]];....
Quoting the right hand side makes bash treat the contents of a as a
string rather than a pattern. If you want the contents treated as a
pattern (or in this case, an ERE) then remove the quotes.
a='^h.$'
if [[ "hi" =~ $a ]]; ...
In fact, putting the ERE-pattern you want to match against into a variable
and then using =~ $variable *is* the recommended practice, if you need to
use =~ at all. It is the only way to get consistent results among all
the different releases of bash that have =~, since the behavior changed
multiple times during the 3.x series.
In this particular case, I would use a glob rather than an ERE, because
"h?" is much simpler than "^h.$".