For an array (let's say arr
), just referring to the array using usual variable reference notation $arr
is analogous to ${arr[0]}
i.e. this refers to the first element of the array. This is what happening in your case.
If you want to refer to the all elements of the array, you almost always want to use "${arr[@]}"
, not "${arr[*]}"
. Because, in the latter case, when quoted like this, the elements would be shown as a single string with the first character of IFS
as separator, by default (when IFS
is space, tab, newline), space becomes the separator.
In the case where ${arr[@]}
is unquoted, it expands to all the elements of the array with word splitting and pathname expansion taking place further.
Here's an example for you:
$ a=( 11 22 )
$ printf '%s\n' "$a"
11
$ printf '%s\n' "${a[0]}"
11
printf '%s\n' "${a[*]}"
11 22
$ printf '%s\n' "${a[@]}"
11
22
Now, in case of b=$(echo "11 22")
, you are simply doing command substitution and inside that running echo "11 12"
(in a subshell), and the result is being saved on variable b
, which is not an array. Hence, you get 11 12
when echo
-ing $b
.
Note that, the right side of variable assignment does not go through word splitting, hence the string 11 12
is saved to variable b
even if there is space between them.
$(echo "11 22")
is no array at all. It's a command substitution. – David Foerster Jul 30 '17 at 21:10