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?

share|improve this question
feedback

3 Answers

up vote 0 down vote accepted

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.

share|improve this answer
feedback

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).

share|improve this answer
feedback

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
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.