Skip to main content
1 of 2
ilkkachu
  • 147.8k
  • 16
  • 268
  • 441

In Bash and ksh, expanding an array as if it was a normal string variable, gives the first element of the array. That is, $somearray is the same as ${somearray[0]}.

So,

somearray=(foo bar doo)
echo "$somearray"
echo "$somearray" | wc -w

prints foo and 1, since foo is only one word. If you had somearray=("foo bar doo" "acdc abba") instead, then the wc would show three words.

You'll need to use "${somearray[@]}" to expand all elements of the array as distinct shell words (arguments), or "${somearray[*]}" to expand them as a single shell word, joined with spaces (assuming default IFS).

In any case, note that the number of elements in an array, and the number of words (in the wc -w or the human language sense) are not the same (see below). Use "${#somearray[@]}" to get the number of elements in the array.

somearray=("foo bar doo" "acdc abba")
echo "${#somearray[@]}"                # 2
echo "${somearray[@]}" | wc -w         # 5
ilkkachu
  • 147.8k
  • 16
  • 268
  • 441