解释 bash 中数组长度的 ${#arrayname[@]} 语法? [英] Explain ${#arrayname[@]} syntax for array length in bash?
问题描述
我知道可以通过执行 ${#arrayname[@]}
在 bash 中获得数组的长度.
I know that one can get the length of an array in bash by doing ${#arrayname[@]}
.
我的问题是:这只是我必须记住的东西,还是可以将这种语法分解为可以理解的部分?例如,@
符号表示人们希望在哪里找到索引?为什么是 #
?
My question is: is this just something that I have to memorize, or can this syntax be broken down into understandable parts? For instance, what does the @
symbol mean where one would expect to find the index? Why the #
?
推荐答案
#
在变量引用的开头表示获取变量值的长度.对于普通变量,这意味着它的长度(以字符为单位).#
是数字"符号,因此您可以将其记住为变量中事物的数量".
#
at the beginning of a variable reference means to get the length of the variable's value. For a normal variable this means its length in characters. #
is the "number" sign, so you can remember this as meaning "the number of things in the variable".
@
或 *
在数组索引中表示使用整个数组,而不是特定元素,它返回的不是字符数,而是字符数数组元素.*
在许多上下文中用作通配符,因此这应该很容易记住.此外,$*
和 $@
用于表示 shell 脚本的所有参数,因此与所有数组元素的并行应该是显而易见的.
@
or *
in an array index means to use the whole array, not a specific element, and instead of returning the number of characters, it returns the number of array elements. *
is used as a wildcard in many contexts, so this should be easy to remember. Also, $*
and $@
are used to mean all the arguments to a shell script, so the parallel with all the array elements should be obvious.
你不能只写${#arrayname}
,因为当你使用一个没有下标的数组变量时,它相当于数组的元素0
.所以${#arrayname}
和${#arrayname[0]}
是一样的,都是数组第一个元素的字符数.
You can't just write ${#arrayname}
because when you use an array variable without a subscript, it's equivalent to element 0
of the array. So ${#arrayname}
is the same as ${#arrayname[0]}
, which is the number of characters in the first element of the array.
这篇关于解释 bash 中数组长度的 ${#arrayname[@]} 语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!