This question already has an answer here:
I want to create some scripts for filling some templates and inserting them into my project folder. I want to use a shell script for this, and the templates are very small so I want to embed them in the shell script. The problem is that echo
seems to ignore the line breaks in my string. Either that, or the string doesn't contain line breaks to begin with. Here is an example:
MY_STRING="
Hello, world! This
Is
A
Multi lined
String."
echo -e $MY_STRING
This outputs:
Hello, world! This Is A Multi lined String.
I'm assuming echo
is the culprit here. How can I get it to acknowledge the line breaks?
echo
is so nineties. The new (POSIX) kid on the block isprintf
.No
-e
or SYSV vs BSD echo madness and full control over what gets printed where and how wide, escape sequences like in C. Everybody please start usingprintf
now and never look back.Try this :
You need double quotes around the variable interpolation.
This is an all-too common error. You should get into the habit of always quoting strings, unless you specifically need to split into whitespace-separated tokens or have wildcards expanded.
So to be explicit, the shell will normalize whitespace when it parses your command line. You can see this if you write a simple C program which prints out its
argv
array.By contrast, with quoting, the whole string is in
argv[0]
, newlines and all.For what it's worth, also consider here documents (with
cat
, notecho
):You can also interpolate a variable in a here document.
... although in this particular case, it's hardly what you want.