nagualcode
nagualcode

Reputation: 57

BASH: How to pass strings from array as arguments to a command?

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.

Upvotes: 0

Views: 98

Answers (1)

glenn jackman
glenn jackman

Reputation: 247210

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

Upvotes: 1

Related Questions