Whitespace Is Collapsed with Echo >>

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

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

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.