关于git:错误:checkout会覆盖以下未跟踪的工作树文件

error: The following untracked working tree files would be overwritten by checkout

当我做git status的时候,上面写着nothing to commit, working directory clean

然后我做git pull --rebase,它说:

1
2
3
4
5
6
First, rewinding head to replay your work on top of it...
error: The following untracked working tree files would be overwritten by checkout:
    includes/resources/moduledata/12/_Fr4_02_Invention_IPA_SR_la-Fe?te.pdf
Please move or remove them before you can switch branches.
Aborting
could not detach HEAD

执行git pull origin master时的类似错误

1
2
3
4
5
 * branch            master     -> FETCH_HEAD
error: The following untracked working tree files would be overwritten by merge:
    includes/resources/moduledata/12/_Fr4_02_Invention_IPA_SR_la-Fe?te.pdf
Please move or remove them before you can merge.
Aborting

我的.gitignore文件:

1
2
3
→ cat .gitignore
.htaccess
bower_components/

这个文件一直不断出现,当我从文件系统中删除它时,Git会说我删除了这个文件,而在其他消息中,它说它是未跟踪的。如何在同一时间释放和跟踪它?


这也可能由于文件名的大小写更改而发生。我也有同样的问题,这就是我解决它的原因。

1
git config core.ignorecase true

适用于Mac或PC。

备选解决方案:签出将覆盖以下未跟踪的工作树文件


如果没有回购的完整图片,接下来的事情更像是猜测,但它可能解释了这种情况。假设您的历史如下:

1
2
3
A -- C [origin/master]
  \
   B [HEAD, master]

你写:

This file has been coming up constantly and when I remove it from file system, git will say I removed this file, while in the other messages, it says it is untracked.

我猜你可能跑了

1
git rm --cached <file-in-question>

并在commit B中进行了删除;因此,该文件不再在本地repo中跟踪,但仍存在于您的工作树中。

同时,上游分支从您的一个合作者那里收到commit C,其中没有从版本控制中删除。你想要影响的

1
git pull --rebase

是这样的:

1
2
3
 A -- C [origin/master]
       \
        B' [HEAD, master]

然而,正如消息所说,

The [...] untracked working tree

would be overwritten by checkout

实际上,重绕commit C(为了重放上面的B)会导致在工作树中签出(从commit C签出),其中已经存在同名的未跟踪文件。该未跟踪文件的内容可能很有价值;您可能不希望该文件被其他版本的文件覆盖。因此,Git会停在它的轨道上,告诉你出了什么问题。

编辑:这里有一个婴儿的例子,复制了这种情况…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
cd ~/Desktop
mkdir test
cd test
git init
touch README.md
git add README.md
git commit -m"add README"

# simulate a remote branch moving ahead by one commit
# (that doesn't remove the README)
git checkout -b origin_master
printf"This is a README.
"> README.md
git add README.md
git commit -m"add description in README"

# remove the README and create a new commit on master
git checkout master
git rm --cached README.md
git commit -m"remove README"

# simulate an attempt to rebase master to its"upstream" branch, origin_master
git rebase --onto origin_master master

最后一个命令发出以下命令:

1
2
3
4
5
6
First, rewinding head to replay your work on top of it...
error: The following untracked working tree files would be overwritten by checkout:
    README.md
Please move or remove them before you can switch branches.
Aborting
could not detach HEAD

我建议你跑步

1
2
git fetch
git log --stat origin/master..master -- <file-in-question>

检查是否发生了类似的事情。


删除所有未跟踪的文件(carefull):

1
git clean  -d  -fx""