cizixs cizixs - 6 months ago 29
Bash Question

Multi-line string with extra space (preserved indentation)

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

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

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 '' VARIABLE << EOM
This is line 1.
This is line 2.
Line 3.
EOM

This stores the lines to the variable named VARIABLE.

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 more stand out in your code. This time just add a '-' after '<<' to stop the tabs from appearing.

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

But then you must use tabs not spaces for indentation.

Comments