3

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?

  • 2
    Simple answer is your quoting. You need to quote the variable name" echo "${NUMBERS}'and three'" – Valentin Bajrami Dec 3 '16 at 16:37
  • You are right. Quoting the variable name will indeed solve my problem. On the other hand, it will prevent Field Splitting with advanced IFS cases. – Robert Novotny Dec 3 '16 at 17:06
  • Quoting is important in most cases since file names in *nix can have spaces, newlines, special chars etc – Valentin Bajrami Dec 3 '16 at 17:07
4

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.

  • Oh! I was under impression that the Field Splitting is applied piece-wise to the expansion results ("the shell shall scan the results of expansions and substitutions"). So the Field Splitting starts at the echo and ends after the last apostrophe? And since there is no IFS whitespace before echo and after three', this section does not apply? – Robert Novotny Dec 3 '16 at 17:11

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.