有时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
#

当前回答

Git rm——cached用于从索引中删除文件。在文件已经在repo的情况下,git rm——cached将从索引中删除该文件,将其留在工作目录中,现在提交也将从repo中删除该文件。基本上,在提交之后,您将取消该文件的版本控制,并保留一个本地副本。

git重置HEAD文件(默认使用——mixed标志)的不同之处在于,在文件已经在repo的情况下,它会用repo (HEAD)中的索引版本替换文件的索引版本,有效地取消对它的修改。

在未版本化文件的情况下,它将取消整个文件,因为该文件不在HEAD中。在这方面,git reset HEAD file和git rm——cached是一样的,但它们是不一样的(就像已经在repo中的文件一样)

对于为什么在git中有两种方法取消文件的问题?-在git中从来没有真正只有一种方法来做任何事情。这就是它的美妙之处:)

其他回答

>并不取消文件,它实际上是从repo中删除文件(假设它之前已经提交),但将文件留在你的工作树中(留下一个未跟踪的文件)。

git reset——<filePath>将取消对给定文件的任何阶段性更改。

也就是说,如果您使用缓存在一个新文件上的git rm—,它基本上看起来就像您刚刚取消了它的暂存,因为它之前从未提交过。

更新git 2.24 在这个新版本的git中,你可以使用git restore - staging而不是git reset。 参见git文档。

Git rm——cached用于从索引中删除文件。在文件已经在repo的情况下,git rm——cached将从索引中删除该文件,将其留在工作目录中,现在提交也将从repo中删除该文件。基本上,在提交之后,您将取消该文件的版本控制,并保留一个本地副本。

git重置HEAD文件(默认使用——mixed标志)的不同之处在于,在文件已经在repo的情况下,它会用repo (HEAD)中的索引版本替换文件的索引版本,有效地取消对它的修改。

在未版本化文件的情况下,它将取消整个文件,因为该文件不在HEAD中。在这方面,git reset HEAD file和git rm——cached是一样的,但它们是不一样的(就像已经在repo中的文件一样)

对于为什么在git中有两种方法取消文件的问题?-在git中从来没有真正只有一种方法来做任何事情。这就是它的美妙之处:)

仅适用于版本2.23及以上,

除了这些建议,你可以使用 Git恢复—staging <文件>,以便取消文件的阶段。

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

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

丢弃局部更改

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

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

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

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

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…”取消舞台)

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