Multi-dimensional arrays in Bash

scphantm picture scphantm · Jun 27, 2012 · Viewed 176.5k times · Source

I am planning a script to manage some pieces of my Linux systems and am at the point of deciding if I want to use or .

I would prefer to do this as a Bash script simply because the commands are easier, but the real deciding factor is configuration. I need to be able to store a multi-dimensional array in the configuration file to tell the script what to do with itself. Storing simple key=value pairs in config files is easy enough with bash, but the only way I can think of to do a multi-dimensional array is a two layer parsing engine, something like

array=&d1|v1;v2;v3&d2|v1;v2;v3

but the marshall/unmarshall code could get to be a bear and its far from user friendly for the next poor sap that has to administer this. If i can't do this easily in bash i will simply write the configs to an xml file and write the script in python.

Is there an easy way to do this in bash?

thanks everyone.

Answer

Nahuel Fouilleul picture Nahuel Fouilleul · Jun 27, 2012

Bash does not support multidimensional arrays, nor hashes, and it seems that you want a hash that values are arrays. This solution is not very beautiful, a solution with an xml file should be better :

array=('d1=(v1 v2 v3)' 'd2=(v1 v2 v3)')
for elt in "${array[@]}";do eval $elt;done
echo "d1 ${#d1[@]} ${d1[@]}"
echo "d2 ${#d2[@]} ${d2[@]}"

EDIT: this answer is quite old, since since bash 4 supports hash tables, see also this answer for a solution without eval.