Emulating two-dimensional (or even multi-dimensional) arrays in bash

Ever needed to use arrays of two or more dimensions but got stuck on Bash limited array support which provides only 1 dimension?

There is a trick that let's you dynamically create variable names. Using this, you can emulate additional dimensions.

Here's a simple example for an array with 2 dimensions:

#set the value of my_array[i][j] where i = 25 and j = 10 to "value"

var="my_array25-10"
#or like this: I=25;J=10;var="my_array$I-$J"

declare $var="value"
#retrieve the value of my_array[i][j] where i = 5 and j = 10
var="my_array5-10"
#or like this: I=5;J=10;var="my_array$I-$J"
echo ${!var}

Thanks to the guys from #bash on freenode for their help and their excellent bash faq

Add comment