Search code examples
bashshelldash-shellbuilt-in

Why is read acting differently in bash and dash?


This is an attempt to find out how is the read utility working in several shells. Found a difference that seems like a bug to me.

Results are that dash retains trailing spaces with read:

dash: <a b     >
bash: <a b>

In short: Why this code perform differently in bash and dash read?

dash -c 'echo "    a b     " | { read var; echo "<$var>"; }'
bash -c 'echo "    a b     " | { read var; echo "<$var>"; }'

Solution

  • Here's an easier way of demonstrating your issue:

    $ dash -c 'echo "a b     " | { read var; echo "<$var>"; }'
    <a b     >
    $ bash -c 'echo "a b     " | { read var; echo "<$var>"; }'
    <a b>
    

    This only happens when there are two or more fields, like "a b ", and not when there is just one, like "a ".

    Here's what POSIX says (emphasis mine):

    If there are fewer vars than fields, the last var shall be set to a value comprising the following elements:

    • The field that corresponds to the last var in the normal assignment sequence described above

    • The delimiter(s) that follow the field corresponding to the last var

    • The remaining fields and their delimiters, with trailing IFS white space ignored

    dash does not ignore the trailing IFS white space, so it appears to be in violation of POSIX.

    The bash behavior is correct.