Loosing trailing new line in Bash var assignment

I have come across a weird behaviour in bash and would love to get to the bottom of it. If I execute

echo -e "\na\nb\nc\n"

at the command line, I get:

a
b
c

However, if I wrap it in an assignment such as:

A="$( echo -e "\na\nb\nc\n" )"

then I get

a
b
c

It doesn't show very well, but it has no trailing new line. It is as if the assignment is loosing the trailing new line (everything after the 'c'). Does anyone know how to turn this off?

A="\na\nb\nc\n"

Shows up as:

 ~ $ printf "$A"

a
b
c
+ ~ $ 

Or if using echo:

+ ~ $ echo -e "$A"

a
b
c

:) ~ $ 

That is, as echo always prints a 'newline' char at the end of a line automaticly, also with -e , eventhough, that is needed to supply more 'format commands'.
printf on the other hand, handles 'format commands' with ease, but it just prints everything 'on one line', thus, you need to append the tailing \n , where as with echo -e you had gotten an extra newline.

hth

This has nothing to do with echo or print. It is how POSIX defines command substitution.

To put it concisely, with command substitution, verbatim assignment of arbitrary text is impossible.

Regards,
Alister

When I do

 A="$( echo -e "\nb\nc\nd\n" )"
set | grep ^A
A=$'\nb\nc\nd'

So, it does look as if the command substitution strips the whitespace at the end. Many thanks for clearing this up!!

Anyone with any idea of a way of negating this effect, I would love to hear from them!! :slight_smile:

There is none.

Perhaps if you provided us with the big picture, someone could suggest an alternative. What are you trying to accomplish?

Regards,
Alister