我使用命令错误地将文件添加到 Git :

git add myfile.txt

我还没有执行 git 承诺 。 我如何撤销此操作, 使这些更改不被包含在承诺中 ?


当前回答

取消对未承诺更改的修改的 git 添加 :

git reset <file>

这将将文件从当前索引( “ 即将被承诺” 列表) 中删除, 而不更改其它内容 。


取消所有文件的所有更改 :

git reset

在旧版本的 Git 中, 上述命令分别相当于 git 重置 HEAD < file > 和 git 重置 HEAD, 如果 HEAD 未定义( 因为您尚未在仓库中做出任何承诺) 或含糊不清( 因为您创建了一个名为 HEAD 的分支, 这是您不应该做的蠢事 ) , 则上述命令将失败。 但是, 在 Git 1.8. 2 中, 这被更改了 。 因此, 在现代版本的 Git 中, 您可以在第一次承诺之前使用上面的命令 :

当您在历史中没有任何承诺时, “ 将重置” (没有选项或参数) 用于错误退出, 但它现在给了您一个空索引( 匹配不存在的重置, 您甚至没有在 ) 。

文献资料:Git重置

其他回答

如上文所述,从中转区删除新文件(仅在出现新文件的情况下):

git rm --cached FILE

使用 rm -- -- 刻录仅用于新文件不小心添加 。

使用 git 添加 - i 来从您即将做出的承诺中删除仅添加的文件。 例如 :

添加您不想添加的文件 :

$ git add foo
$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   foo
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
# [...]#

进入交互式添加以取消您的添加( 这里输入的 git 命令是“ r”( revert) , “ 1”( 列表返回显示的第一个条目) , “ return” 退出返回模式, 以及“ q” ( quit) :

$ git add -i
           staged     unstaged path
  1:        +1/-0      nothing foo

*** Commands ***
  1: [s]tatus     2: [u]pdate     3: [r]evert     4: [a]dd untracked
  5: [p]atch      6: [d]iff       7: [q]uit       8: [h]elp
What now> r
           staged     unstaged path
  1:        +1/-0      nothing [f]oo
Revert>> 1
           staged     unstaged path
* 1:        +1/-0      nothing [f]oo
Revert>> 
note: foo is untracked now.
reverted one path

*** Commands ***
  1: [s]tatus     2: [u]pdate     3: [r]evert     4: [a]dd untracked
  5: [p]atch      6: [d]iff       7: [q]uit       8: [h]elp
What now> q
Bye.
$

这就是你的证据 证明"foo"又回到了未追踪的名单上

$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
# [...]
#       foo
nothing added to commit but untracked files present (use "git add" to track)
$

对于特定文件 :

git 重置我的檔案. txt git 檢查我的檔案. txt

对于所有添加的文件 :

git 重新设置. git 检查退出 。

注意: 检出将文件的代码更改, 并移动到上次更新( 承诺) 状态。 重置不会更改代码; 它只是重置信头 。

如果您想要还原最后一个任务, 但仍要保留在任务中本地作出的更改, 请使用此命令 :

git reset HEAD~1 --mixed

运行运行中

git gui

,然后手动删除所有文件,或者选择全部文件,然后从执行按钮中单击非阶段。