0
#!/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]=$j
    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
=> run result:
           1         2         3         4   
 1         1         1         1         1
 2         2         2         2         2
 3         3         3         3         3
 4         4         4         4         4
 5         5         5         5         5

======================== #!/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]=$i
    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

if change assignment to the array from $j to $i the result:

           1         2         3         4
 1         4         4         4         4
 2         4         4         4         4
 3         4         4         4         4
 4         4         4         4         4
 5         4         4         4         4

This seems because bash doesn't support multi-dimensional array?

Is there a way to use two dimensional array with bash?

3
  • Correct, bash doesn't support multi-dimensional arrays. Thus, ${arr[x,y]} is exactly the same as ${arr[y]}, as the comma is a math operator that simply evaluates to the value on its right. Commented Jul 16, 2015 at 23:09
  • stackoverflow.com/questions/16487258/… is another dupe; likewise, unix.stackexchange.com/questions/109434/… Commented Jul 16, 2015 at 23:11
  • I've had a lot more success with a mixture of bash and gawk. But, if you can, use something like matlab or julia for multi-dimensional arrays. Commented Jul 17, 2015 at 3:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.