How to force Git to use LF instead of CRLF

For some reasons you may want to change all line endings of your text files to LF instead of CRLF, here is how to do it.

1. Create a .gitattributes file at the root of your project

Specify the files that you want end of line (eol) to change by using regex.

Here is a sample file for a Java project:

# Handle line endings automatically for files detected as text
# and leave all files detected as binary untouched.
* text=auto

#
# The above will handle all files NOT found below
#
# These files are text and should be normalized (Convert crlf => lf)
*.css           eol=lf
*.df            eol=lf
*.htm           eol=lf
*.html          eol=lf
*.java          eol=lf
*.js            eol=lf
*.json          eol=lf
*.jsp           eol=lf
*.jspf          eol=lf
*.jspx          eol=lf
*.properties    eol=lf
*.sh            eol=lf
*.tld           eol=lf
*.txt           eol=lf
*.tag           eol=lf
*.tagx          eol=lf
*.xml           eol=lf
*.yml           eol=lf

# These files are binary and should be left untouched
# (binary is a macro for -text -diff)
*.class         binary
*.dll           binary
*.ear           binary
*.gif           binary
*.ico           binary
*.jar           binary
*.jpg           binary
*.jpeg          binary
*.png           binary
*.so            binary
*.war           binary

2. Remove all project files

git rm --cached -rf /path/to/your/project

3. Re-create all files (from source tree)

git diff --cached --name-only -z | xargs -n 50 -0 git add -f

The above command does:

  • a diff between your local project and your local git repository, because you have deleted all files it will return all file names from source tree
  • read results from ‘git diff’ and pass the file names to ‘git add’ (thanks to ‘xargs’)
  • add back all files, and this time the EOL policy will be applied thanks to the .gitattributes file

4. Commit and push your changes

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.