2

I want to create a config file with a .sh file. I can't figure out how i insert new lines.

The code i already have:

domainconf='<VirtualHost *:80>\n ServerName '$fulldomain'\n DocumentRoot '$fullpath'\n </VirtualHost>'
echo $domainconf > /etc/apache2/sites-available/"$fulldomain".conf
itspat
  • 21
  • 4

4 Answers4

5

If all you need to do is to write the configuration to a file, then the following would be more readable, and it does away with the need for a variable:

cat >/etc/apache2/sites-available/"$fulldomain".conf <<END_CONFIG
<VirtualHost *:80>
ServerName '$fulldomain'
DocumentRoot '$fullpath'
</VirtualHost>
END_CONFIG

If you absolutely need the thing in a variable:

conf=$(cat <<END_CONFIG
<VirtualHost *:80>
ServerName '$fulldomain'
DocumentRoot '$fullpath'
</VirtualHost>
END_CONFIG
)

echo "$conf" >/etc/apache2/sites-available/"$fulldomain".conf
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
  • Does command substitution need double quoting? – Kevin Jul 05 '16 at 19:36
  • @Kevin You may quote the command substitution if you wish, but it's not necessary here (because here-document). The important bit is the quoting of `$conf` in `echo "$conf"`. – Kusalananda Jul 06 '16 at 06:02
  • 1
    @Kevin I'm actually unsure about it, but since I can't seem to get it to *fail* without quoting (for various odd here-doc contents), I believe it's safe. Please feel free to prove me wrong. – Kusalananda Jul 06 '16 at 06:04
  • 2
    @Kevin not when it is the value in an assignment, although otherwise it usually does. Kusalananda: Try `echo $( cat < – dave_thompson_085 Jul 06 '16 at 06:14
  • @dave_thompson_085 Much appreciated, thanks! – Kusalananda Jul 06 '16 at 06:30
2

Just echo with '-e' flag

domainconf='<VirtualHost *:80>\n ServerName '$fulldomain'\n DocumentRoot '$fullpath'\n </VirtualHost>'
echo -e "$domainconf" > /etc/apache2/sites-available/"$fulldomain".conf
terdon
  • 234,489
  • 66
  • 447
  • 667
  • 1
    Welcome to Unix & Linux @Patrick! If this answer solved your issue, please take a moment and [accept it](http://unix.stackexchange.com/help/someone-answers) by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites. – terdon Jul 05 '16 at 15:12
2

Another option is to embed literal newlines in the script:

% cat newl  
blah='x
y
z'

echo "$blah"
% sh newl 
x
y
z
% 

Do note the quotes on $blah!

thrig
  • 34,333
  • 3
  • 63
  • 84
1

Try to replace echo by printf

domainconf='<VirtualHost *:80>\n ServerName '$fulldomain'\n DocumentRoot '$fullpath'\n </VirtualHost>'
printf "$domainconf" > /etc/apache2/sites-available/"$fulldomain".conf
  • `printf` is a pretty good solution, but not the way you've used it (which is no better than `echo`). Try `domfmt='\n ServerName %s\n DocumentRoot %s\n '` followed by `printf "$domfmt" "$fulldomain" "$fullpath" > "/etc/apache2/sites-available/$fulldomain.conf"` – cas Jul 06 '16 at 01:04