bug-bash
[Top][All Lists]
Advanced

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

Re: associative arrays and [[ -v


From: Chet Ramey
Subject: Re: associative arrays and [[ -v
Date: Fri, 17 Apr 2015 12:32:55 -0400
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:31.0) Gecko/20100101 Thunderbird/31.6.0

On 4/17/15 5:12 AM, isabella parakiss wrote:
> I need to check if an element in an associative array is set.  What's the
> correct way to test it?

If *any* element is set, or if a particular element is set?

> 
> 
> $ declare -A arr=([x]=y); var=*
> $ [[ -v arr["$var"] ]]; echo $?
> 0
> $ [[ ${arr["$var"]} ]]; echo $?
> 1
> 
> 
> The former seems wrong, the glob is expanded even if "$var" is quoted.

It's not a glob.  The array subscripts `@' and `*' are special and expand
to all elements of an array.

> The latter works but it doesn't distinguish between unset and empty.

The distinction is murky.  A variable is not set unless it has been
assigned a value.  Has an array variable that has no elements been
assigned a value?  Is the concept of a=() meaningful and useful?

> Is there a way to test it with ''[[ -v'' ?

Are you interested in whether or not an array has been declared or whether
it has any elements?

> Also this one seems wrong, found by geirha:
> 
> $ declare -A a=([x]=y); [[ -v a ]]; echo $?
> 1
> $ declare -A a=(["0"]=y); [[ -v a ]]; echo $?
> 0

Referencing an array without a subscript is equivalent to referencing
element 0.

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]