Why should text files end with a newline?

后端 未结 18 1222
栀梦
栀梦 2020-11-21 22:56

I assume everyone here is familiar with the adage that all text files should end with a newline. I\'ve known of this \"rule\" for years but I\'ve always wondered — why?

18条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 23:21

    There's also a practical programming issue with files lacking newlines at the end: The read Bash built-in (I don't know about other read implementations) doesn't work as expected:

    printf $'foo\nbar' | while read line
    do
        echo $line
    done
    

    This prints only foo! The reason is that when read encounters the last line, it writes the contents to $line but returns exit code 1 because it reached EOF. This breaks the while loop, so we never reach the echo $line part. If you want to handle this situation, you have to do the following:

    while read line || [ -n "${line-}" ]
    do
        echo $line
    done < <(printf $'foo\nbar')
    

    That is, do the echo if the read failed because of a non-empty line at end of file. Naturally, in this case there will be one extra newline in the output which was not in the input.

提交回复
热议问题