108

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

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?

codeforester
  • 39,467
  • 16
  • 112
  • 140
bob dobbs
  • 1,133
  • 2
  • 7
  • 5

1 Answers1

214

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.

Martin
  • 37,119
  • 15
  • 73
  • 82
  • 5
    Thanks, now I finally understand why echo works like this - because it parses the input as arguments! I wish I read that somewhere earlier. – Paul Feb 03 '15 at 22:47
  • Tangentially, see also http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable – tripleee Feb 28 '17 at 10:52