2

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Chris Maes
  • 35,025
  • 12
  • 111
  • 136

1 Answers1

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 character
  • read builtin exits nonzero if it detects EOF 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