echo removes double spaces

on

I had this script which appended the output of an echo of a string to a file..

loop
  echo $string >> file.txt
done

But this removed all double (or more) spaces from the string. In fact the file contained only nicely single spaced lines, perfectly formated. But this was not the intention.

Echo did som strange things.

The theory of this phenomenon is that echo handles all words as an independent parameter. And fact is that in bash double spaces are removed from an parameter list.

echo hello    my   name is Knilluz

is handled the same as

echo hello my name is Knilluz

So a simple solution is: use quotes

echo "$string" >> file.txt

now the string is handled as one parameter and all spaces are preserved.
ie.

knilluz@serv:~$ echo Hello     my   name is    Knilluz
Hello my name is Knilluz
knilluz@serv:~$ echo "Hello     my   name is    Knilluz"
Hello     my   name is    Knilluz

But hey, the other way around, it’s a method to clean up strings.