Shell – ${#array} vs ${#array[@]}

arrayscriptingshell-scriptzsh

As far as I can tell both ${#array[@]} and ${#array} evaluate to the number of elements in $array. Is there any reason for preferring the longer form (${#array[@]})?

Best Answer

In zsh, personal preference. In other shells $array may only expand to the first element, thus ${#array} would output the length of the first element.

So, if you want to be little more portable between shells specifying the [@] would work.

In zsh, $array expands in the same way $array[*] would, which differs depending on if they appear within quotes or not. Should they appear within double quotes "$array" would expand and be delimited by the first character of IFS which by default is space

zsh% touch {1..10}; a=(*)
zsh% printf '<%s> ' $a
<1> <10> <2> <3> <4> <5> <6> <7> <8> <9>     
zsh% printf '<%s> ' "$a"
<1 10 2 3 4 5 6 7 8 9> 
zsh% IFS=:
zsh% print "$a"
1:10:2:3:4:5:6:7:8:9
zsh% print "$a[@]"
1 10 2 3 4 5 6 7 8 9
zsh% IFS=$' \t\n'
zsh% rm "$a"
rm: cannot remove ‘1 10 2 3 4 5 6 7 8 9’: No such file or directory

Changing IFS is rarely needed which prompted my original "Personal preferences" response. But just to clarify there is a few differences between the two when used without the # flag, they are is just very subtle.

I prefer $array[@] also since it's behavior doesn't change depending on whether or not it appears within quotes. That and internal whitespace that an element may have is preserved.

Related Question