tags:

views:

28

answers:

3
bash-3.00$ cat arr.bash  
#!/bin/bash  

declare -a myarray  
myarray[2]="two"  
myarray[5]="five"  

echo ${#myarray[*]}  
echo ${#myarray[@]}  

bash-3.00$ ./arr.bash  
2  
2

both are giving number of elements of array. So what is difference between the two?

A: 

There is no difference. From the bash manpage:

${#name[subscript]} expands to the length of ${name[sub‐script]}. If subscript is * or @, the expansion is the number of elements in the array.

psmears
+2  A: 

In this case, there is no difference. The two "all elements" subscripts make a difference when you expand the array and the expansion is surrounded by quotes.

"${array[*]} expands to "two five"

"${array[@]} expands to "two" "five" (i.e. two words).

Aaron Digulla
+1  A: 

There is no difference. They both give the number of elements in the array. The difference comes when you use the array expansion "${array[*]}" in double quotes and have IFS set to some value other than the default.

$ array=(1 2 3)
$ echo "${array[*]}"
1 2 3
$ saveIFS=$IFS
$ IFS=","
$ echo "${array[*]}"
1,2,3
$ IFS=$saveIFS
Dennis Williamson