Skip to main content
  1. Posts/

Git line ending config

·450 words·3 mins·
Git Git
Table of Contents

This post is about how to set up Git so that people using different operating systems can work in the same repository, without messing up the line ending of source files.

Settings for personal use (not good, not recommended)#

We can change the core.autocrlf setting:

git config --global core.autocrlf true

By setting core.autocrlf to true, if your original file line ending is CRLF, it will not change, but when you commit your files, git will normalize the line ending to LF.

After the above setup, you can run the following command:

git add --renormalize .

This will put the normalized text files in your repo to the git index, You can then commit the changes:

git commit -m "Renormalize line ending to LF"

Note that the files in your local working tree still have original line ending. For example, if foo.py has CRLF line ending, and bar.py has LF line ending, they will remain so in your working tree.

For repository
#

The above setting is not enforceable, because everyone has to set it up individually. So it is not really ideal way to make sure everyone has the correct line ending setup.

We can use the .gitattributes file to enforce this. Create a file named .gitattributes in the root directory of the project:

* text=auto

# mark this file as always have crlf line ending on checkout
*.bat text eol=crlf

# mark pattern as binary file
*.jpg binary

The setting here will overwrite the core.autocrlf setting.

We can then run the re-normalize command to normalize the line ending:

git add --renormalize .
git commit -m "Renormalize line ending to LF"

But this will not change the line ending for the file in the working tree. If we run the following command:

git ls-files --eol

It shows something like this:

i/lf    w/lf    attr/text=auto          .gitattributes
i/lf    w/lf    attr/text=auto          another-file.md
i/lf    w/crlf  attr/text=auto          demo.txt
i/lf    w/crlf  attr/text eol=crlf      execute.bat

i/lf means the file copy at index is using LF line ending. w/lf or w/crlf means the line ending used in the working tree. In this case, for demo.txt, the file copy in the working tree is still using the CRLF line ending.

To correct this and use LF line ending also for text file not explicitly specified to use CRLF, we can run the following command:

git rm --cached -r .
git reset --hard HEAD

After this, if you run the ls-files command again, you should be able to see something like this:

i/lf    w/lf    attr/text=auto          .gitattributes
i/lf    w/lf    attr/text=auto          another-file.md
i/lf    w/lf    attr/text=auto          demo.txt
i/lf    w/crlf  attr/text eol=crlf      execute.bat

References
#

Related

How to Use The Git-tag Feature
··285 words·2 mins
Git Git
Git Learning Notes (2)
··410 words·2 mins
Git Git Vim
Git Learning Notes (1)
··701 words·4 mins
Git Git Diff