tl;dr
printf "%s\n" "${x[*]}"
Explanation
echo
takes 3 options:
$ help echo
[…]
Options:
-n do not append a newline
-e enable interpretation of the following backslash escapes
-E explicitly suppress interpretation of backslash escapes
So if you run:
$ echo -n
$ echo -n -e
$ echo -n -e -E
You get nothing. Even if you put each option in quotes, it still looks the same to bash:
$ echo "-n"
$ echo "-n" "-e"
The last command runs echo
with two arguments: -n
and -e
. Now contrast that with:
$ echo "-n -e"
-n -e
What we did was run echo
with a single argument: -n -e
. Since bash does not recognize the (combined) option -n -e
, it finally echoes the single argument to the terminal like we want.
Applied to Arrays
In the second case, the array x
begins with the element -e
. After bash expands the array ${x[@]}
, you are effectively running:
$ echo "-e" "2" "-e"
2 -e
Since the first argument is -e
, it is interpreted as an option (instead of echoed to the terminal), as we already saw.
Now contrast that with the other style of array expansion ${x[*]}
, which effectively does the following:
$ echo "-e 2 -e"
-e 2 -e
bash sees the single argument -e 2 -e
— and since it does not recognize that as an option — it echoes the argument to the terminal.
Note that ${x[*]}
style expansion is not safe in general. Take the following example:
$ x=(-e)
$ echo "${x[*]}"
Nothing is printed even though we expected -e
to be echoed. If you've been paying attention, you already know why this is the case.
Escaping
The solution is to escape any arguments to the echo
command. Unfortunately, unlike other commands which offer some way to say, “hey! the following argument is not to be interpreted as an option” (typically a --
argument), bash provides no such escaping mechanism for echo
.
Fortunately there is the printf
command, which provides a superset of the functionality that echo
offers. Hence we arrive at the solution:
printf "%s\n" "${x[*]}"