'Why does bash keep adding a leading whitespace to the variable?

var="               bar" (the whitespace is intentional)

echo foo${var}

produces

foo bar ("var" has leading whitespace)

but

echo ${var}

produces

bar ("var" has no leading whitespace)

Why? Is this a bug in bash 4.2.37(2)?



Solution 1:[1]

Unquoted whitespace is removed by word-splitting after parameter (variable) expansion. The leading space is what echo outputs between its arguments.

Your first example,

echo foo${var}

results in the strings foo and bar separated by a large amount of whitespace, which bash only uses to treat the two strings as separate arguments, which echo outputs separated by a single space. Your second example,

echo ${var}

presents echo with a single argument, bar, with a large amount of whitespace separating the command and the argument.

Quoting the parameter expansions in each case preserves all the whitespace in the parameter value.

$ var="               bar"
$ echo "foo${var}"
foo               bar
$ echo "${var}"
               bar

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dannysauer