string="0123456789" # create a string of 10 characters
array=(0 1 2 3 4 5 6 7 8 9) # create an indexed array of 10 elements
declare -A hash
hash=([one]=1 [two]=2 [three]=3) # create an associative array of 3 elements
echo "string length is: ${#string}" # length of string
echo "array length is: ${#array[@]}" # length of array using @ as the index
echo "array length is: ${#array[*]}" # length of array using * as the index
echo "hash length is: ${#hash[@]}" # length of array using @ as the index
echo "hash length is: ${#hash[*]}" # length of array using * as the index
输出:
string length is: 10
array length is: 10
array length is: 10
hash length is: 3
hash length is: 3
处理$@,参数数组:
set arg1 arg2 "arg 3"
args_copy=("$@")
echo "number of args is: $#"
echo "number of args is: ${#@}"
echo "args_copy length is: ${#args_copy[@]}"
输出:
number of args is: 3
number of args is: 3
args_copy length is: 3
7条答案
按热度按时间6rvt4ljy1#
0mkxixxg2#
来自巴什manual:
${#参数}
将替换形参的扩展值的字符长度。如果形参是""或"@",则替换的值是位置形参的数目。如果形参是下标为""或"@"的数组名称,则替换的值是数组中的元素数目。如果形参是下标为负数的索引数组名称,该数字被解释为相对于大于参数的最大索引的1,因此负索引从数组末尾开始往回计数,索引-1引用最后一个元素。
字符串、数组和关联数组的长度
输出:
处理
$@
,参数数组:输出:
xv8emn3q3#
假设猛击:
因此,
${#ARRAY[*]}
扩展为数组ARRAY
的长度。a5g8bdjr4#
在tcsh或csh中:
xtfmy6hx5#
在Fish Shell中,数组的长度可通过下式求出:
x6h2sr286#
这对我来说很有效:
xzabzqsa7#
对于那些还在寻找将数组长度放入变量的方法的人: