Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I preserve newlines in a quoted string in Bash? [duplicate]

Tags:

bash

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?

like image 577
bob dobbs Avatar asked Mar 10 '10 02:03

bob dobbs


People also ask

Is variable empty bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"


1 Answers

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.

like image 174
Martin Avatar answered Oct 25 '22 20:10

Martin