为什么bash
似乎要对数组中的单词进行计数而不是对元素数量进行计数?
touch '1 red' '2 orange' '3 yellow' # Three filenames, each of two words
files=( * ) # Get the set of files
echo "#files is ${#files}"
for (( i=0; i <= ${#files}; i++ ))
do
printf "%d\t%s\n" $i "${files[$i]}"
done
这样的输出似乎是“错误的”。对于初学者,${#files}
包含5
,表明中有六个元素${files[@]}
。但是,只有元素0
,1
和2
和${files[@]}
包含任何数据,并且包含正确的文件名:
#files is 5
0 1 red
1 2 orange
2 3 yellow
3
4
5
我本来期望要么${files[@]}
包含了六个字1
,red
,2
,orange
,3
,和yellow
,或者${#files}
是2
。不是这种混合方案。
请问有人可以帮我一下吗?
${#files}
是数组第一个元素的长度,即的长度1 red
。五个。
从手册:
$ {#name [subscript]}的长度扩展为$ {name [subscript]}。如果下标为'@'或'*',则扩展为数组中元素的数量。[...]
引用不带下标的数组变量等效于引用带下标0的引用。
因此,${#files}
= ${#files[0]}
。但是${#files[@]}
或${#files[*]}
给出数组中元素的数量。
(这与单词的数量无关,尽管如果${files[*]}
不加引号进行扩展,则会在所有值上分割出通常的单词。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句