简体   繁体   English

如何在bash中获得二维数组的第二维的大小?

[英]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 ? 获得第二维或arr大小的正确方法是什么?

Multi-dimensional arrays are not supported in BASH. 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 ) : 两者都被评估为arr[10]=anything (谢谢chepner

echo ${arr[10]}
anything

Bash doesn't have multi-dimensional array. Bash没有多维数组。 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. 您要做的是,除非您已将arr变量声明为关联数组,否则甚至不会模拟多维数组。 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[@]} 你只能用${arr[@]}来获得整体的大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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