Can I have nested Associative Maps in Linux Shell?
2 Answers
No, bash array are only one dimensional. You should be able to construct your array keys to fake multi-dimensionality. For example, if you want the JSON object
x = {'foo': {'a': 1, 'b': 2}, 'bar': {'c': 3, 'd', 4}}
in bash, you would have to do something like
declare -A x
x[foo,a]=1
x[foo,b]=2
x[bar,c]=3
x[bar,d]=4
and reference with, for example
i=foo
j=b
echo "${x[$i,$j]}"
Comments
Yes!
Take a look at man bash!
(search for associative)
But if you want to assign array to array, you have to declare sub objects for itself, whit his own handler, than you may assign this handler as a string to upper array:
declare -A x
declare -A x_foo
x_foo=([a]=1 [b]=3)
x['foo']=x_foo;
so
echo ${!x[@]}
foo
echo ${x[foo]}
x_foo
eval echo \${${x[foo]}[a]}
1
eval echo \${${x[foo]}[b]}
3
eval echo \${!${x[foo]}[@]}
a b
eval echo \${${x[foo]}[@]}
1 3
1 Comment
user1460043
It is mentioned in stackoverflow.com/a/3467959/1460043 that usage of
eval to simulate associative arrays has issues.