如何在 Bash 中保留带引号的字符串中的换行符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2414150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:01:33  来源:igfitidea点击:

How do I preserve newlines in a quoted string in Bash?

bash

提问by bob dobbs

I'm creating a script to automate the creation of apache virtual hosts. Part of my script goes like this:

我正在创建一个脚本来自动创建 apache 虚拟主机。我的部分脚本是这样的:

MYSTRING="<VirtualHost *:80>

ServerName $NEWVHOST
DocumentRoot /var/www/hosts/$NEWVHOST

...

"
echo $MYSTRING

However, the line breaks in the script are being ignored. If I echo the string, is gets spat out as one line.

但是,脚本中的换行符将被忽略。如果我回显字符串,它会作为一行吐出。

How can I ensure that the line breaks are printed?

如何确保打印换行符?

回答by Martin

Add quotes to make it work:

添加引号以使其工作:

echo "$MYSTRING"

Look at it this way:

这样看:

MYSTRING="line-1
line-2
line3"

echo $MYSTRING

this will be executed as:

这将被执行为:

echo line-1 \
line-2 \
line-3

i.e. echowith three parameters, printing each parameter with a space in between them.

echo有三个参数,打印每个参数之间有一个空格。

If you add quotes around $MYSTRING, the resulting command will be:

如果在 周围添加引号$MYSTRING,则生成的命令将是:

echo "line-1
line-2
line-3"

i.e. echowith a single string parameter which has three lines of text and two line breaks.

echo具有单个字符串参数,其中包含三行文本和两个换行符。