Search code examples
bashescapingvar

bash variable eats multiple spaces, turning them to one


# export var="many      spaces"; echo =${var}=
=many spaces=

What is going on here? Why multiply spaces are turned to one? How to keep all?


Solution

  • You’re simply missing quotations around your variable. Changing your code to this:

    $ export var="many      spaces"; echo ="${var}"=
    =many      spaces=
    

    should give the result you’re looking for. One “feature” of bash that you need to watch out for is word splitting, which is based on the value of your IFS (internal field separator) variable. Typically IFS defaults to

    IFS=$' \t\n'
    

    so you need to take care in quoting variables that contain spaces, tabs, and newlines.