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 c...@case.edu http://cnswww.cns.cwru.edu/~chet/