如何在Bourne Shell中回显多行字符串 [英] How to echo multi lined strings in a Bourne shell

查看:78
本文介绍了如何在Bourne Shell中回显多行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一些脚本来填充一些模板并将其插入到我的项目文件夹中.我想为此使用shell脚本,并且模板很小,因此我想将它们嵌入shell脚本中.问题是echo似乎忽略了我的字符串中的换行符.要么,要么该字符串不包含换行符开始.这是一个示例:

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

这将输出:

Hello, world! This Is A Multi lined String.

我假设echo是这里的罪魁祸首.我怎样才能知道换行符?

I'm assuming echo is the culprit here. How can I get it to acknowledge the line breaks?

推荐答案

您需要在变量插值周围加上双引号.

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.

因此,明确地说,shell在解析您的命令行时将规范空格.如果您编写一个简单的C程序并打印出它的argv数组,就可以看到这一点.

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.'

与之相反,用引号将整个字符串放在argv[0]中,包括换行符和所有内容.

By contrast, with quoting, the whole string is in argv[0], newlines and all.

对于它的价值,还请考虑以下文档(使用cat,而不是echo):

For what it's worth, also consider here documents (with cat, not echo):

cat <<"HERE"
foo
Bar
HERE

您还可以在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.

这篇关于如何在Bourne Shell中回显多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆