molecule molecule - 4 months ago 6
Bash Question

How to avoid spaces in echo when it is split into multiple lines

I have a very long string to be printed by

echo
command. By doing so I want it to be perfectly indented.
I am trying this and it is perfectly working fine

echo "This is a very long string. An"\
"d it is printed in one line"

Output:
This is a very long string. And it is printed in one line


But as I try to indent it properly as the echo statement is also indented. It adds an extra space.

echo "This is a very long string. An"\
"d it is printed in one line"

Output:
This is a very long string. An d it is printed in one line


I can't find any working response which will do this perfectly.

Answer

To problem here is that you are giving two arguments to echo, and its default behaviour is to prints them back with a space in between:

$ echo "a"             "b"
a b
$ echo "a" "b"
a b
$ echo "a"\
>           "b"
a b

If you want to have full control on what you are printing, use printf with an array:

lines=("This is a very long string. An"
       "d it is printed in one line")
printf "%s" "${lines[@]}"
printf "\n"

This will return:

This is a very long string. And it is printed in one line

Interesting reading: Why is printf better than echo?.