git
doesn't like files that don't end with a newline (see this question for example). Suppose I want to clean up my repository and make sure each file ends properly with a newline (without adding useless newlines), is there some kind of tool or command that could help me do this?
Asked
Active
Viewed 865 times
2

jonrsharpe
- 115,751
- 26
- 228
- 437

Chris Maes
- 35,025
- 12
- 111
- 136
1 Answers
4
for f in $(git grep --cached -Il ''); do tail -c1 $f | read -r _ || echo >> $f; done
explanation
git grep --cached -Il ''
lists all text files in the git index (link)tail -c1
reads the last characterread
builtin exits nonzero if it detectsEOF
before it finds a\n
echo >> $f
is only executed when the read command fails
ps: inspired by https://backreference.org/2010/05/23/sanitizing-files-with-no-trailing-newline/

Chris Maes
- 35,025
- 12
- 111
- 136
-
1Will this break binary files? – EncryptedWatermelon Sep 03 '19 at 12:08
-
2@EncryptedWatermelon very good remark. I changed the script to affect only text files. – Chris Maes Sep 03 '19 at 13:53