<script src="//cdn.optimizely.com/js/187642160.js"></script>

handling CRLF in git

If you use git on windows or cygwin, I am sure you’ve encountered this.

$ git add dir/newfile
fatal: LF would be replaced by CRLF in dir/newfile

While there is much confusion/discussion around how to handle this using core.autocrlf and core.safecrlf config attributes, I have lately settled with this recommendation:

Basically, what it boils down to is we should try to keep all text files in CRLF form on windows/cygwin. And the default value of true for core.autocrlf/safecrlf take care of switching it to LF when checkin/out of git repository.

So, when the above error occurs, what it means is that the file is in unix format and I am on windows machine. In order to make git happy, we need to convert it to DOS format (using unix2dos.exe utility on cygwin).

However, it is a pain to do this on each modified/added file 17 times a day. So, I created following ruby script:

$ cat ~/bin/fix_crlf

out = `git status`.split("\n").select do |line|
paths = out.collect do |line|
  line = line.sub("#\t","")
  line = line.sub("modified:   ","")
paths.each do |path|
  `unix2dos.exe #{path}`

This takes care of updating all your modified/new files in proper CRLF format.

It is not perfect, but it works good-enough for me. Is there a better way to handle this?

  1. Carl Reply

    Thanks. Here’s what I use on an msysgit BASH shell on windows:
    git status | grep modified | sed -E ‘s/#\t* *modified: *//g’ | while read x; do todos -p “$x”; done

    It assumes that you want to convert the line endings of everything. Todos can be obtained from http://www.thefreecountry.com/tofrodos/index.shtml, the same guys responsible for making unix2dos.

Leave a Reply


captcha *