3

In Bash, the arrays a=( 11 22 ) and b=$(echo "11 22") behave differently when printed.

$ a=( 11 22 )
$ b=$(echo "11 22")
$ echo $b
11 22
$ echo $a
11

If we want to print the full contents of a we have to resort to printing it as ${a[*]}, as opposed to $a.

What explains this difference in behavior between an array assignment by parenthesis and one by command substitution?

2 Answers2

4

Thanks for the below Note from @cas:
$b is NOT an array, it is a string containing "11 22"

The equivalent to

a=( 11 22 )

Is

b=($(echo "11 22"))

As a result

$ a=( 11 22 )
$ b=($(echo "11 22"))
$ echo $a
11
$ echo ${a[*]}
11 22
$ echo $b
11
$ echo ${b[*]}
11 22
Yaron
  • 4,289
  • 3
    +1. answer is correct but you neglected to point out the key fact that in the question, $b is NOT an array, it is a string containing "11 22". – cas Jul 30 '17 at 14:30
3

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.

heemayl
  • 56,300