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

我正在创建一个脚本来自动创建 apache 虚拟主机:

MYSTRING="<VirtualHost *:80>


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


...


"
echo $MYSTRING

但是,脚本中的换行符将被忽略。如果我重复这个字符串,就会像一行一样被吐出来。

如何确保打印了换行符?

57127 次浏览

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. echo with three parameters, printing each parameter with a space in between them.

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

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

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