How to echo multi lined strings in a Bourne shell [duplicate]

怎甘沉沦 提交于 2019-11-28 11:01:57

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.

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.

Try this :

echo  "$MY_STRING"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!