Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare 2D array in bash

Tags:

linux

bash

shell

I'm wondering how to declare a 2D array in bash and then initialize to 0.

In C it looks like this:

int a[4][5] = {0}; 

And how do I assign a value to an element? As in C:

a[2][3] = 3; 
like image 681
Anis_Stack Avatar asked May 10 '13 16:05

Anis_Stack


People also ask

How do you declare a 2D array?

To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.

Does bash support multidimensional arrays?

Since Bash does not support 2D arrays out of the box, we must come up with our own way to use them. Let's explore common implementations.

How do you declare 2D?

We can declare a two-dimensional integer array say 'x' of size 10,20 as: int x[10][20]; Elements in two-dimensional arrays are commonly referred to by x[i][j] where i is the row number and 'j' is the column number.


1 Answers

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]}
like image 161
jm666 Avatar answered Oct 20 '22 05:10

jm666