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?
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.