git: new blank line at EOF

Maxim Chetrusca picture Maxim Chetrusca · Nov 21, 2014 · Viewed 14.1k times · Source

So I run git diff --check before add-ing files and commit-ing them, and on two specific files I get path/filename:linenumber: new blank line at EOF. If I delete the last empty line in those files, I don't get any messages, but I think it is good style to end my files with a newline. Strangely enough, the other files which I think have exactly the same endings, don't give any messages. I am new to git, using git 2.0.1 on OS X Yosemite. I use vim as my editor.

How can I have my files end with newline while avoiding this message? Should I ignore it?

Answer

romainl picture romainl · Nov 21, 2014

There are two issues, here.

  • you are confused about "newline" vs "new line":

    A "new line" is an actual empty line (contains only a "newline" character) and a "newline" is a special character used to mark the end of the current line.

    Most compilers, interpreters and Unix tools expect your text files to end with a newline to avoid ambiguity when dealing with multiple files, not a "new line".

    Most editors, Vim included, add that necessary character at the end of every line, last line included, so there's nothing to do on your side to ensure that requirement is met.

    Especially not adding a "new line" at the EOF.

  • you are probably used to bad behavior:

    The "newline" character is traditionally interpreted as a "line terminator" by Unix tools, most compilers and Vim. This means that whatever comes after that character is considered to be on another line. Since that character is the last one in the file, there's no reason to show a line that is not there to the user.

    Alas, most GUI editors interpret it as a "line separator", meaning that it marks the separation between two lines and those editors usually show a non-existing line at the end of your file to satisfy that interpretation.

    I'm probably assuming too much, but it looks like you are used to that wrong behavior and try to mimic it by adding a totally unnecessary "new line" at the end of your files.

Either you keep adding "new lines" at the bottom of your source files, consider that as some sort of formatting and coding guideline and stop considering those Git messages as error messages.

Or you stop adding those useless "new lines".

I would go with the second option.