How to get the size of the second dimension of two dimensional arrays in bash?

If I have

arr[0,0]=0;
arr[0,1]=1;

      

And i try

echo ${#arr[0,@]}

      

I got

bash: 0,@: syntax error: operand expected (error token is "@")

      

What is the correct way to get the size of the second dimension or arr

?

+3


source to share


2 answers


Multidimensional arrays are not supported in BASH.
However, you can imitate them using various methods.

The following definitions are the same:

  • arr[1,10]=anything

  • arr["1,10"]=anything



Both are evaluated as arr[10]=anything

(thanks to chepner ):

echo ${arr[10]}
anything

      

+3


source


Bash doesn't have a multidimensional array. What you are trying to do will not even simulate a multidimensional array unless you have declared the variable arr

as an associative array. Check out the following test:

#!/bin/bash
arr[0,0]=0
arr[0,1]=1
arr[1,0]=2
arr[1,1]=3
echo "${arr[0,0]} ${arr[0,1]}" # will print 2 3 not 0 1
unset arr
declare -A arr
arr[0,0]=0
arr[0,1]=1
arr[1,0]=2
arr[1,1]=3
echo "${arr[0,0]} ${arr[0,1]}" # will print 0 1

      



And you can only get the size in general with ${arr[@]}

0


source







All Articles