Multi-line string with extra space (preserved indentation)

cizixs picture cizixs · May 29, 2014 · Viewed 499.4k times · Source

I want to write some pre-defined texts to a file with the following:

text="this is line one\n
this is line two\n
this is line three"

echo -e $text > filename

I'm expecting something like this:

this is line one
this is line two
this is line three

But got this:

this is line one
 this is line two
 this is line three

I'm positive that there is no space after each \n, but how does the extra space come out?

Answer

new-kid picture new-kid · May 29, 2014

Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like ex or cat

cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage

The string after << indicates where to stop.

To send these lines to a file, use:

cat > $FILE <<- EOM
Line 1.
Line 2.
EOM

You could also store these lines to a variable:

read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM

This stores the lines to the variable named VAR.

When printing, remember the quotes around the variable otherwise you won't see the newline characters.

echo "$VAR"

Even better, you can use indentation to make it stand out more in your code. This time just add a - after << to stop the tabs from appearing.

read -r -d '' VAR <<- EOM
    This is line 1.
    This is line 2.
    Line 3.
EOM

But then you must use tabs, not spaces, for indentation in your code.