bug-bash
[Top][All Lists]
Advanced

[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: Sat, 18 Apr 2015 00:47:25 +0200

(Sorry the previous message lacked the declaration of var, it was an
asterisk obviously)

$ var=*
$ declare -A arr=([a]=b)
$ [[ -v arr['$var'] ]]; echo $?
1
$ declare -A arr=(['*']=x)
$ [[ -v arr['$var'] ]]; echo $?
0



---
xoxo iza

On 4/18/15, isabella parakiss <izaberina@gmail.com> wrote:
> On 4/17/15, Chet Ramey <chet.ramey@case.edu> wrote:
>> 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/
>>
>
> I'm interested to test if the element '*' is set.
>
>
> 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?
>
>
>
> ---
> xoxo iza
>



reply via email to

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