[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: This errors in 4.4, did not in 4.2: set -u; declare -A foo; echo ${#
From: |
#!microsuxx |
Subject: |
Re: This errors in 4.4, did not in 4.2: set -u; declare -A foo; echo ${#foo[@]} |
Date: |
Thu, 7 Nov 2024 23:39:01 +0100 |
On Thu, Nov 7, 2024, 23:36 #!microsuxx <fxmbsw7@gmail.com> wrote:
>
>
> On Thu, Nov 7, 2024, 21:10 Chet Ramey <chet.ramey@case.edu> wrote:
>
>> On 11/6/24 9:38 PM, David Linden wrote:
>>
>> > Bash Version: 4.4
>> > Patch Level: 20
>> > Release Status: release
>> >
>> > Description:
>> > This errors in 4.4, did not in 4.2: set -u; declare -A foo; echo
>> ${#foo[@]}
>>
>> Yes, this was a bug in bash-4.2, fixed in bash-4.3. A variable isn't set
>> until it's been assigned a value. This fix aligns the array variable
>> behavior with the scalar (non-array) variable behavior.
>>
>>
>> > How am I supposed to determine that a declared associative array
>> is empty?
>>
>
> to try to answer ' how to check if assoc arr is empty '
> first [[ ${name@a} == *A* ]] or == A not sure
>
> then in code
>
> ~/m $ cat m.test.emptyassoc
> #!/bin/bash
>
> c() {
> local r=$@
> eval -- "$r"
> l
> }
>
> l() {
> l1
> }
>
> r() {
> eval "$@" &&
> echo -e "$@\t\t$r"
> }
>
> l1() {
> r [[ -v $n ]]
> r "(( \${#$n[@]} ))"
> }
>
> unset -v assoc n
> n=assoc
>
> c : init
> c declare -A assoc
> c 'assoc+=( foo bar )'
> c 'assoc+=( 2foo 2bar )'
> c unset -v $n
>
> ~/m $ bash m.test.emptyassoc
> [[ -v assoc ]] assoc+=( foo bar )
> (( ${#assoc[@]} )) assoc+=( foo bar )
> [[ -v assoc ]] assoc+=( 2foo 2bar )
> (( ${#assoc[@]} )) assoc+=( 2foo 2bar )
>
> therefore [[ -v and (( $# works
>
> That's not the question that `set -u' answers. It will tell you whether
>> a variable with attributes (or without) has been assigned a value.
>>
>> Does your code manage this variable? If it does, you should be able to
>> determine whether or not it was ever assigned a value, or make sure
>> that it has been assigned a value, if that's important. The empty array
>> is a valid value, just like the empty string is a valid value for scalar
>> variables.
>>
>> > Or even use it in a conditional even one where the value won't be
>> evaluated?
>
>
[[ -v assoc[\$elem] ]] if set , not checked if empty or not
else
[[ ${assoc[$elem]} ]]
what
>
> What do you mean? Using something like foo[@] is fine in expansions
>> where it won't be expanded:
>>
>> echo ${foo[@]-unset}
>>
>> or
>>
>> v=set; echo ${v:-foo[@]}
>>
>> But if you get into a case where the variable needs to be expanded,
>> you're going to get an error if the variable isn't set.
>>
>> --
>> ``The lyf so short, the craft so long to lerne.'' - Chaucer
>> ``Ars longa, vita brevis'' - Hippocrates
>> Chet Ramey, UTech, CWRU chet@case.edu http://tiswww.cwru.edu/~chet/
>>
>