Bash: Multi-dimensional Arrays

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.

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.

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.

ibrahim = { interested_in(unix, linux, android, open_source, reverse_engineering); coding(c, shell, perl, php, python, java, javascript, nodejs, angular, react); plays_on(xbox, ps4); linux_desktop_user(true); }