有时git会建议git rm——cached来取消文件,有时git会重置HEAD文件。什么时候用哪个?

D:\code\gt2>git init
Initialized empty Git repository in D:/code/gt2/.git/
D:\code\gt2>touch a

D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       a
nothing added to commit but untracked files present (use "git add" to track)

D:\code\gt2>git add a

D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#       new file:   a
#
D:\code\gt2>git commit -m a
[master (root-commit) c271e05] a
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 a

D:\code\gt2>touch b

D:\code\gt2>git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       b
nothing added to commit but untracked files present (use "git add" to track)

D:\code\gt2>git add b

D:\code\gt2>git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   b
#

当前回答

1.

D:\code\gt2>git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#       new file:   a

(使用“git rm—cached…”取消阶段)

Git是一个指针系统 您还没有要更改指针的提交 “从指向的桶中取出文件”的唯一方法是删除你告诉git观察变化的文件

2.

D:\code\gt2>git commit -m a
[master (root-commit) c271e05] a
0 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 a

Git提交-m a

你承诺了,“拯救了”

3.

D:\code\gt2>git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   b
#

(使用“git reset HEAD…”取消舞台)

此时,您在代码中进行了一次提交 现在你可以重置指针指向你提交的"恢复到上次保存"

其他回答

在我看来,git rm——cached <file>从索引中删除了文件,而没有从目录中删除它,而普通的git rm <file>将两者都做,就像OS rm <file>将从目录中删除文件而没有删除它的版本。

如果你无意中暂存了不想提交的文件,并且想要确保保留更改,你也可以使用:

git stash
git stash pop

这将执行HEAD重置并重新应用您的更改,允许您重新提交单个文件。如果你忘记了为pull请求创建一个特性分支(git stash;Git checkout -b <feature>;Git stash pop)。

假设你通过git add <folder>暂存整个目录,但是你想从暂存列表(即运行git状态时生成的列表)中排除一个文件,并将修改保留在排除的文件中(你正在做一些事情,它还没有准备好提交,但你不想失去你的工作…)你可以简单地使用:

Git重置<文件>

当您运行git status时,您将看到您重置的任何文件都是非暂存的,而您添加的其余文件仍然在暂存列表中。

取消暂存文件(取消git添加)

将file.js的最后一个版本从repo复制到index

丢弃局部更改

将file.js从索引复制到工作目录

file2.js #恢复工作目录下的多个文件

Git恢复。#丢弃所有本地更改(除了未跟踪的文件)

git clean -fd #删除所有未跟踪的文件

我很惊讶没有人提到git reflog (http://git-scm.com/docs/git-reflog):

# git reflog
<find the place before your staged anything>
# git reset HEAD@{1}

reflog是一个git历史记录,它不仅跟踪对repo的更改,还跟踪用户的操作(例如。拉,签出到不同的分支等),并允许撤销这些操作。因此,与其取消被错误地暂存的文件,还不如恢复到没有暂存文件的位置。

这类似于git reset HEAD <file>,但在某些情况下可能更细粒度。

抱歉,我并没有真正回答你的问题,只是指出了另一种方法来取消我经常使用的文件(我非常喜欢Ryan Stewart和waldyrious的答案);)我希望这能有所帮助。