是否有可能取消git中最后一个暂存(未提交)的更改?假设当前分支中有很多文件,有些是阶段性的,有些不是。在某个时刻,某个愚蠢的程序员不小心执行了:

git add -- .

...而不是:

git checkout -- .

这个程序员现在可以用一些神奇的git命令取消他最后的更改吗?或者他应该在一开始尝试之前就做出承诺?


你不能撤销最新的git添加,但是你可以撤销自上次提交以来的所有添加。Git reset不带commit参数会重置索引(取消阶段性变化):

git reset

你可以使用git重置(见文档)


你可以使用git重置。这将“取消”你上次提交后添加的所有文件。

如果你只想取消一些文件,使用git reset——<file 1> <file 2> <file n>。

此外,还可以使用git reset -p取消文件中的一些更改。


根据难度的大小和规模,您可以创建一个临时分支,并将当前的工作提交到那里。

然后切换到原始分支并签出,并从从头提交中选择适当的文件。

至少您将拥有当前和以前的状态的永久记录(直到您删除那个scratch分支为止)。


所以真正的答案是

这个程序员现在可以用一些神奇的git命令取消他最后的更改吗?

实际上是:不,你不能只取消最后一个git添加。

也就是说,如果我们在以下情况下解释这个问题:

最初的文件:

void foo() {

}

main() {
    foo();
}

git添加的第一个变化:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

git添加后的第二个变化:

void foo(int bar, String baz) {
    print("$bar $baz");
}

main() {
    foo(1337, "h4x0r");
}

在这种情况下,git reset -p将不起作用,因为它的最小粒度是行。Git不知道中间状态:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

任何更多的。


在date git提示:

如果文件不在repo中,使用"git rm——cached <file>…"它会取消文件,把它们保存在那里。 使用“git reset HEAD <file>…”如果文件在repo中,则取消阶段,并按修改后的方式添加它们。它保持文件原样,并取消它们的阶段。

据我所知,您无法撤消git add—但您可以取消上面提到的文件列表。


Remove the file from the index, but keep it versioned and left with uncommitted changes in working copy: git reset head <file> Reset the file to the last state from HEAD, undoing changes and removing them from the index: git reset HEAD <file> git checkout <file> # If you have a `<branch>` named like `<file>`, use: git checkout -- <file> This is needed since git reset --hard HEAD won't work with single files. Remove <file> from index and versioning, keeping the un-versioned file with changes in working copy: git rm --cached <file> Remove <file> from working copy and versioning completely: git rm <file>


如果你想从git中删除所有添加的文件

git reset

如果要删除单个文件

git rm <file>

你可以使用

git reset

撤销最近添加的本地文件

 git reset file_name

来撤消对特定文件的更改


我建议使用:

Git rm -r——cached <your_dir>或Git rm——cached <your_file>

它会还原你的

git add <your_dir_or_your_file>

回去,同时保持文件原样。