0

Each string in "list_of_arrays", is the name of an array I need to pass to the 'declare' command line.

Something like:

for arrayname in "${list_of_arrays[@]}"; do 
declare -A idx=(["$arrayname[0]"]=0 ["$arrayname[1]"]=0 ["$arrayname[2]"]=0 ...)
done

How do I make this work for any number of strings? Each string/array name will always be unique.

0

1 Answer 1

1

You'll need to use indirect variables to accomplish this:

foo=(a b c)
baz=(g h i)
bar=(d e f)
list_of_arrays=(foo bar baz)
for aname in "${list_of_arrays[@]}"; do 
    unset idx; declare -A idx
    tmp="${aname}[@]"
    for value in "${!tmp}"; do 
        idx[$value]=0
    done
    # print it out to verify
    declare -p idx
done
declare -A idx='([a]="0" [b]="0" [c]="0" )'
declare -A idx='([d]="0" [e]="0" [f]="0" )'
declare -A idx='([g]="0" [h]="0" [i]="0" )'

Well, all of the above is wrong, as the OP wants the array names to be the keys of the idx array. As mentioned in the comments:

tmp=( "${list_of_arrays[@]/#/[}" ) 
tmp=( "${tmp[@]/%/]=0}" )
eval declare -A idx=( "${tmp[@]}" )

Although I would go with the much less clever:

declare -A idx
for aname in "${list_of_arrays[@]}"; do idx["$aname"]=0; done
declare -p idx
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Glenn! can I use: tmp=( "${list_of_arrays[@]/#/[}" ) tmp=( "${tmp[@]/%/]=0}" ); declare -A "$(printf '%s ' "${tmp[@]}")" ?
That mostly works, except I get this error when I declare -A idx=( "${tmp[@]}" ) ==> bash: idx: "${tmp[@]}": must use subscript when assigning associative array, so you need eval declare -A idx=( "${tmp[@]}" )
However, that leads to declare -A idx='([bar]="0" [baz]="0" [foo]="0" )' == do you want the keys if the idx array to be the array names, or the array values?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.