Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make 3D array in BASH?

I want to write/make/use a 3D array of [m][n][k] in BASH. From what I understand, BASH does not support array that are not 1D.

Any ideas how to do it?

like image 213
user3206874 Avatar asked Jan 30 '26 21:01

user3206874


2 Answers

Fake multi-dimensionality with a crafted associative array key:

declare -A ary
for i in 1 2 3; do 
    for j in 4 5 6; do 
        for k in 7 8 9; do 
            ary["$i,$j,$k"]=$((i*j*k))
        done
    done
done
for key in "${!ary[@]}"; do printf "%s\t%d\n" "$key" "${ary[$key]}"; done | sort
1,4,7   28
1,4,8   32
1,4,9   36
1,5,7   35
1,5,8   40
1,5,9   45
1,6,7   42
1,6,8   48
1,6,9   54
2,4,7   56
2,4,8   64
2,4,9   72
2,5,7   70
2,5,8   80
2,5,9   90
2,6,7   84
2,6,8   96
2,6,9   108
3,4,7   84
3,4,8   96
3,4,9   108
3,5,7   105
3,5,8   120
3,5,9   135
3,6,7   126
3,6,8   144
3,6,9   162

I used sort because keys of an assoc.array have no inherent order.

like image 198
glenn jackman Avatar answered Feb 01 '26 11:02

glenn jackman


You can use associative arrays if your bash is recent enough:

unset assoc
declare -A assoc
assoc["1.2.3"]=x

But, I'd rather switch to a language that supports multidimensional arrays (e.g. Perl).

like image 33
choroba Avatar answered Feb 01 '26 10:02

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!