简体   繁体   中英

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 ?

Multi-dimensional arrays are not supported in BASH.
Nevertheless, you could simulate them using various techniques .

The following definitions are the same:

  • arr[1,10]=anything
  • arr["1,10"]=anything

Both are evaluated to arr[10]=anything (thanks chepner ) :

echo ${arr[10]}
anything

Bash doesn't have multi-dimensional array. What you are trying to do, won't even simulate a multi-dimensional array unless you have declared the arr variable 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 as a whole with ${arr[@]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM