Objective: Use multi-dimensional arrays in bash
shell.
Bash
4 provides one-dimensional indexed and associative array variables but does not have support multi-dimensional arrays, but there’s a way to emulate it.
There are indexed arrays and associative arrays in bash
and we can use associative arrays to somehow emulate a multi-dimensional array.
Below is how an indexed array looks like. An indexed array is defined using delare -a
option.
1 2 3 4 5 6 7 8 9 |
declare -a array1 array1[0]='hello' array1[1]='world' echo ${array1[0]} ${array1[1]} hello world echo length of array: ${#array1[@]} length of array: 2 |
Below is an associative array that is defined using delare -A
option. For associative arrays, we can use a any hash as the key, so we can define a key as 0,0
or 0,1
to emulate a 2-dimenional array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
declare -A array2 array2[0,0]='h' array2[0,1]='e' array2[0,2]='l' array2[0,3]='l' array2[0,4]='o' array2[1,0]='w' array2[1,1]='o' array2[1,2]='r' array2[1,3]='l' array2[1,4]='d' echo ${array2[0,0]}${array2[0,1]}${array2[0,2]}${array2[0,3]}${array2[0,4]} ${array2[1,0]}${array2[1,1]}${array2[1,2]}${array2[1,3]}${array2[1,4]} hello world echo length of array: ${#array2[@]} length of array: 10 |
If declare -A array2
is omitted, bash
will not treat the variable array2
as an associative array.
Note that since multi-dimensional arrays are not really supported in bash
, there’s no way to determine the length of the sub-array, etc, so looping through each element in the sub-array is not something that is supported natively by bash
. You will probably need to come up with your own method to loop through such arrays.