Skip to main content
2 of 4
added 495 characters in body
Stéphane Chazelas
  • 584.6k
  • 96
  • 1.1k
  • 1.7k

To print the number of elements in an array variable in various shells with array support:

  • csh/tcsh/zsh/rc/es/akanga: echo $#array
  • ksh¹/bash¹/zsh: echo "${#array[@]}"
  • fish: count $array
  • yash: 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

¹ 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

Stéphane Chazelas
  • 584.6k
  • 96
  • 1.1k
  • 1.7k