Whitespace is collapsed with echo >>

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

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like