[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: associative arrays and [[ -v
From: |
isabella parakiss |
Subject: |
Re: associative arrays and [[ -v |
Date: |
Mon, 20 Apr 2015 08:07:16 +0200 |
On 4/20/15, Chet Ramey <chet.ramey@case.edu> wrote:
> On 4/17/15 6:45 PM, isabella parakiss wrote:
>
>> This seems the way to go, but I'm not sure I understand why:
>>
>> $ declare -A arr=([a]=b)
>> $ [[ -v arr['$var'] ]]; echo $?
>> 1
>> $ declare -A arr=(['*']=x)
>> $ [[ -v arr['$var'] ]]; echo $?
>> 0
>>
>>
>> What's happening?
>
> Well, as I said before, `*' is special: it expands to all elements of the
> array, in the same way as $*. So you have to protect it through all
> word expansions.
>
> First, each word in the conditional expression is expanded as described in
> the manual page
>
> "tilde expansion, parameter and
> variable expansion, arithmetic expansion, command substitution,
> process substitution, and quote removal are performed."
>
> That leaves the word as 'arr[$var]' (without the quotes, of course). The
> subscript in an associative array reference also undergoes expansions, the
> same ones as the rhs of an assignment statement (pretty much the same as
> above). That expands the $var, leaving arr[*]. Since the check for `*' or
> `@' as a subscript happens before expansion, the shell looks for the `*'
> as an element of the array.
>
> In the first case, it doesn't find it; in the second, it does.
>
> 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/
>
Thanks a lot for the explanation, that was tricky.
---
xoxo iza