1
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?

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.