I want to populate an associative array with successive output from an instruction.
With attention for the quotes, I first tried this
declare -A aa
dict='[TAG1]="VALUE 1" [TAG2]="VALUE 2"'
aa="( ${dict} )"
dict='[TAG3]="VALUE 3" [TAG4]="VALUE 4"'
aa+="( ${dict} )"
declare -p aa
but the variable content is not split in keys and values:
declare -A aa=([0]="( [TAG1]=\"VALUE 1\" [TAG2]=\"VALUE 2\" )( [TAG3]=\"VALUE 3\" [TAG4]=\"VALUE 4\" )" )
While a more explicit version works as expected:
declare -A aa
aa=( [TAG1]="VALUE 1" [TAG2]="VALUE 2" )
aa+=( [TAG3]="VALUE 3" [TAG4]="VALUE 4" )
declare -p aa
So I used a workaround
dict='[TAG1]="VALUE 1" [TAG2]="VALUE 2"'
declare -A aa="( ${dict} )"
dict='[TAG3]="VALUE 3" [TAG4]="VALUE 4"'
declare -A aa+="( ${dict} )"
declare -p aa
that delivers the expected result:
declare -A aa=([TAG4]="VALUE 4" [TAG1]="VALUE 1" [TAG3]="VALUE 3" [TAG2]="VALUE 2" )
Now my ultimate goal was to update an associative array in a function, the array being an argument to the function. Passing the array by reference, it should look something like this
modaa () {
declare -Ag "$1"
local -n ref="$1"
dict='[TAG1]="VALUE 1" [TAG2]="VALUE 2"' # In reality, this is the output of an instruction, i.e. $(lsblk -P ...)
ref+="( ${dict} )" # NOK: Assign "$dict" to key [0]
# declare -A ref+="( ${dict} )" # No effect
# declare -Ag ref+="( ${dict} )" # No effect
# ref+=( [TAG1]="VALUE 1" [TAG2]="VALUE 2" ) # Always works but does not use $dict
echo "${!ref[@]}"
}
But because of the issue explained above, the simpler expression doesn't work:
declare -A aa
modaa aa
declare -p aa
declare -A aa=([0]="( [TAG1]=\"VALUE 1\" [TAG2]=\"VALUE 2\" )" )
and the workaround of using 'declare' each time to update does not work within a function.
Did I miss something or is the solution to parse $dict and assign key/value pairs one by one?
${dict}comming from? is supposed to be arg #2 ($2) or does the function just assume the caller has defined${dict}? please update the question with a few sample calls to the function to include the${dict}values and the results following each function call (eg, output fromdeclare -p array)dictis global, but in my actual script it is defined within the function as the output of an instruction like$(lsblk -P -o name,path,uuid,partuuid,mountpoint | grep -e "${dexp[UUID]}" | sed -E -e 's/([[:alnum:]]+)=/\['"${dexp[ID]}"',\1\]=/g' - )I did not think it relevant and my question was already quite long.