To print the number of elements in an array variable in various shells with array support:
csh/tcsh/zsh/rc/es/akanga:echo $#arrayksh¹/bash¹/zsh:echo "${#array[@]}"fish:count $arrayyash:echo "${array[#]}"- Bourne/POSIX shells (where the only array is
"$@"):echo "$#"
Now for the number of whitespace delimited words in all the elements of an array variable, that's where you may want to use wc -w, but you'd need to feed it the content of all the elements separated by at least one white space for instance with:
printf '%s\n' $array:q | wc -w # csh/tcsh
printf '%s\n' "${array[@]}" | wc -w # ksh/bash/zsh/yash
printf '%s\n' $array | wc -w # fish/zsh/rc/es/akanga
printf '%s\n' "$@" | wc -w # Bourne/POSIX
Or you could do the splitting of the elements into further whitespace-delimited words and count them in the shell itself.
csh/tcsh(split on SPC/TAB/NL)(set noglob; set tmp=($array); echo $#tmp)ksh/bash/yash($IFSsplitting, SPC/TAB/NL by default)(set -o noglob; set -- ${array[@]}; echo "$#")zsh($IFSsplitting, SPC/TAB/NL/NUL by default)echo ${#${=array}}rc/es($ifssplitting):tmp = `{echo $array} echo $#tmpfish(counts all sequences of non-whitespace (according to PCRE) characters):count (string match -ar -- '\S+' $array)Bourne/POSIX (
$IFSsplitting):(set -f; set -- $@; echo "$#")
¹ note that given that ksh/bash arrays are sparse and have indices that start at 0 instead of 1 in every other shell, that number will generally not be the same as the maximum index in the array