Bash – Parameter expansion for variable with leading white space

bashbash-expansionshell-scriptvariable substitution

I keep wondering about strange rules of parameter expansion in shell.

If I declare

NUMBERS="  one   two   "

and if execute the following (note that there is no space between variable and the constant string.)

echo ${NUMBERS}'and three'

Bash (along with Dash and Kornshell) echoes:

one two and three

However, the same output is echoed with:

echo ${NUMBERS} 'and three'

I was under impression that according to 2.6.5 Field Splitting rules, 3a, the IFS whitespace should be ignored at the beginning and at the end of the input while expanding the NUMBERS variable.

Why does the shell at one occasion put the space between the expansion and the constant string and at other times not?

Best Answer

Field splitting occurs after expansion, and IFS whitespace is ignored at the beginning and end of the whole input (to avoid creating fields before the first "logical" field or after the last one). Thus by the time it gets to field splitting, your first example is

echo   one   two   'and three'

which is parsed into fields one, two, and and three; likewise your second example is

echo   one   two    'and three'

which is also parsed into fields one, two, and and three.