How to Declare 2D Array in Bash

How to declare 2D array in bash

You can simulate them for example with hashes, but need care about the leading zeroes and many other things. The next demonstration works, but it is far from optimal solution.

#!/bin/bash
declare -A matrix
num_rows=4
num_columns=5

for ((i=1;i<=num_rows;i++)) do
for ((j=1;j<=num_columns;j++)) do
matrix[$i,$j]=$RANDOM
done
done

f1="%$((${#num_rows}+1))s"
f2=" %9s"

printf "$f1" ''
for ((i=1;i<=num_rows;i++)) do
printf "$f2" $i
done
echo

for ((j=1;j<=num_columns;j++)) do
printf "$f1" $j
for ((i=1;i<=num_rows;i++)) do
printf "$f2" ${matrix[$i,$j]}
done
echo
done

the above example creates a 4x5 matrix with random numbers and print it transposed, with the example result

           1         2         3         4
1 18006 31193 16110 23297
2 26229 19869 1140 19837
3 8192 2181 25512 2318
4 3269 25516 18701 7977
5 31775 17358 4468 30345

The principle is: Creating one associative array where the index is an string like 3,4. The benefits:

  • it's possible to use for any-dimension arrays ;) like: 30,40,2 for 3 dimensional.
  • the syntax is close to "C" like arrays ${matrix[2,3]}

Multi-dimensional arrays in Bash

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.

override of a 2D array cells in bash

The answer is to add

declare -A a

How to make a multi dimensional array Bash

A multidimensional array is just a special case of an associative array in bash 4:

# Make myarray an associative array
declare -A myarray

# Assign some random value
myarray[3,7]="foo"

# Access it through variables
x=3 y=7
echo "${myarray[$x,$y]}"

It works because "3,7" is just a string like any other. It could just as well have been "warthog" or "ThreeCommaSeven". As long as everything else in your code turns the indices 3 and 7 into the string "3,7", it'll work just like a multidimensional array.

two dimension array bash

You're missing the variable declaration as an associative array via -A:

typeset -A matrix

Without that, you seem to get a normal array, and then only the last index is actually used; that explains the (wrong) results you've got.



Related Topics



Leave a reply



Submit