Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is bash swallowing -e in the front of an array [duplicate]

Tags:

bash

Given the following syntax:

x=(-a 2);echo "${x[@]}";x=(-e 2 -e); echo "${x[@]}"

Output:

-a 2
2 -e

Desired output

-a 2
-e 2 -e

Why is this happening? How do I fix?

like image 820
Sam Saffron Avatar asked Jan 15 '14 23:01

Sam Saffron


1 Answers

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[*]}"
like image 73
Michael Kropat Avatar answered Jan 03 '23 15:01

Michael Kropat