How to echo multi lined strings in a Bourne shell

2019-01-18 22:51发布

问题:

This question already has an answer here:

  • When to wrap quotes around a shell variable? 5 answers

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?

回答1:

You need double quotes around the variable interpolation.

 echo -e "$MY_STRING"

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.

argv[0]='Hello,'
argv[1]='world!'
argv[2]='This'
argv[3]='Is'
argv[4]='A'
argv[5]='Multi'
argv[6]='lined'
argv[7]='String.'

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, not echo):

cat <<"HERE"
foo
Bar
HERE

You can also interpolate a variable in a here document.

cat <<HERE
$MY_STRING
HERE

... although in this particular case, it's hardly what you want.



回答2:

echo is so nineties. The new (POSIX) kid on the block is printf.

 printf '%s\n' "$MY_STRING"

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 using printf now and never look back.



回答3:

Try this :

echo  "$MY_STRING"