2

Can I have nested Associative Maps in Linux Shell?

2 Answers 2

6

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]}"
Sign up to request clarification or add additional context in comments.

Comments

4

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

It is mentioned in stackoverflow.com/a/3467959/1460043 that usage of eval to simulate associative arrays has issues.

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.