2017-04-24 66 views

回答

3

试试这个:

#!/bin/bash 
declare -A conect 
for i in "[email protected]" 
do 
    echo $i 
    conect[$i]=0 
done 
echo ${#conect[@]} 

说明:

  • 关联阵列(即索引可能非数字)必须声明为declare -A。如果索引保证为数字,则不需要此操作。
  • ${#foo}是字符串值变量的长度(字符数) ${#conect[@]}是数组的长度(元素数量)。
  • 正如其他人指出的那样,"[email protected]"$*更好,特别是当(引用的)参数可能包含空格时。
+0

它的工作!非常感谢! – clausdia

0

$ *创建IFS分开的一个单独的参数。这就是为什么。使用$ @

What is the difference between "[email protected]" and "$*" in Bash?

编辑 其实,通过@that_other_guy和@Ruud_Helderman(感谢你们)所指出的,我说的是不完全正确。

首先是Mea Culpa,因为这个问题不是完整的解决方案。

但它让我感到奇怪,所以这里是正确的方法。 IFS的差异是一个事实。但是,这只是问题如果你引用“$ *”或“$ @”

for i in "$*" 
do 
    echo $i 
done 

将输出在同一条线上的每个参数而

for i in "[email protected]" 
do 
    echo $i 
done 

会做一次一个。

+0

'f(){for i in $ *;确实回应“循环”;完成; }; f 1 2 3'表明这是虚假的 –

+0

@KuuAku很好的建议,但不是OP问题的原因;注意''* *'周围没有引号。看到这个答案中的例子:http://stackoverflow.com/questions/2761723/what-is-the-difference-between-and-in-shell-scripts#2761739 –

0

您应该使用数组:

for i in "[email protected]" 
+1

优秀的建议,但不是OP的问题的原因;注意''* *'周围没有引号。请参阅此答案中的示例:http://stackoverflow.com/questions/2761723/what-is-the-difference-between-and-in-shell-scripts#2761739 –

+1

好点。谢谢@RuudHelderman –