11

I am creating a script that reads the contents of a file, manipulates the contents and appends to another file (specifically the virtual hosts file). The formatting and whitespace in the output file is important but when I write the contents, the whitespace is stripped out.

VHOST_PATH="/etc/apache2/extra/httpd-vhosts.conf"
TEMPLATE_PATH="./template.conf"
TEMPLATE=$(<TEMPLATE_PATH)
# manipulating $TEMPLATE
echo $TEMPLATE                   #outputs correct whitespace
echo $TEMPLATE >> $VHOST_PATH    #does not output correct whitespace

So the first echo produces something like

<VirtualHost *:80>
    ServerAdmin webmaster@domain
    DocumentRoot "root/web"
    ServerName domain
    ErrorLog "root/logs/error_log"
</VirtualHost>

but the string that gets into the file is

<VirtualHost *:80> ServerAdmin webmaster@domain DocumentRoot "root/web" ServerName domain ErrorLog "root/logs/error_log" </VirtualHost>

How do I preserve the whitespace while appending into the target file? I've searched for this but all the similar questions dont apply to my script without rewriting it.

1 Answer 1

9

Like every other program, echo interprets strings separated by whitespace as different arguments.

After calling

echo foo    bar

the only data that gets passed to echo by the shell is that the first argument is foo and the second is bar.

To pass a whole string containing whitespaces as a single argument, enclose it in double quotes:

echo "foo    bar"

will print all four spaces.

8
  • On a side note: I find it surprising that echo $TEMPLATE would work. It should collapse multiple whitespaces as well.
    – Dennis
    Jan 22, 2013 at 22:07
  • Yes! That was it. It makes complete sense but I didnt realize this was the case. Also, echo $TEMPLATE was working because I had quotes around it but I neglected to copy it over to my post.I didnt think that was important. I was wrong!
    – Jeff
    Jan 22, 2013 at 22:10
  • 1
    @Jeff See the following: Commands and Arguments
    – slhck
    Jan 22, 2013 at 22:21
  • 1
    @Jeff, it's critically important, when seeking assistance, to cut and paste instead of re-typing. Jan 22, 2013 at 23:29
  • @glennjackman i thought i could get away with retyping since the scripts were so short and copy+paste would be a pain since i was working in a terminal. i was wrong. lesson learned. thanks for the tip.
    – Jeff
    Jan 23, 2013 at 14:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .