git commit get fatal error “fatal: CRLF would be replaced by LF in”

筅森魡賤 提交于 2019-11-27 05:57:46
VonC

This is a classic issue:


(picture from Luis Tubes's blog post)

The usual fix is to convert those files yourself, with dos2unix or Swiss File Knife.

I have always preferred to keep core.autocrlf to false, which means:

git config --global core.autocrlf false

I had the same problem and tried the suggested solution with no success.

I had to execute a second command to make it work:

$ git config --global core.autocrlf false
$ git config --global core.safecrlf false
Arun
$ git config core.autocrlf false

One may just try dos2unix:

dos2unix [filename]

This happened to me on thousands of files. So I wrote a quick bash script to make dos2unix fix it for me. Someone else on Linux or Mac might find it useful.

#!/usr/bin/env bash

unwindows() {

  local errmsg
  local fpath

  # base case
  errmsg="$(git add . 2>&1)"
  if [[ $? -eq 0 ]]; then
    echo 'Successfully converted CRLF to LF in all files.'
    echo 'Successfully ran "git add .".'
    echo 'Done.'
    return 0
  fi

  fpath="${errmsg#*fatal: CRLF would be replaced by LF in }"
  fpath="${fpath%.*}"

  if [[ "${fpath}" == "${errmsg}" ]]; then
    err 'Regex failed. Could not auto-generate filename from stderr.'
    return 1
  fi

  if [[ ! -e "${fpath}" ]]; then
    err "Regex failed. '${fpath}' does not exist."
    return 1
  fi

  if ! dos2unix "${fpath}"; then
    err "Failed to run \"dos2unix '${fpath}'\"."
    return 1
  fi

  # recursive case
  unwindows
}

err() {
  local -r msg="$1"
  echo "${msg}" >&2
}

unwindows

Basically, it tries to do git add .. If the command fails, it grabs the name of the incompatible file from the error output. Then it runs dos2unix on that file. It keeps repeating this process until git add . works.

If you run this, you should see dos2unix: converting file xxx to Unix format... repeatedly. If you don't, it's not working, so just press ctrl+c or command+c to stop it.

Karl.S

You need to add all files that git status displays as modified:

git add file1
git add file2

And then commit your changes :

git commit

This will keep your local files as is, but will autocrlf them on the remote repository.

I faced same trouble and fixed with editing .gitattributes as below.

$ vim .gitattributes

comment out 2 lines in .gitattributes

-* text=auto
-* text eol=lf
+# * text=auto
+# * text eol=lf

FYI not sure if this applies to you but I was getting this error when accidentally trying to add all node_modules to the staged changes. So actually .gitignoring the node_modules solved my problem.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!