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

git add -- .

...而不是:

git checkout -- .

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


当前回答

在date git提示:

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

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

其他回答

所以真正的答案是

这个程序员现在可以用一些神奇的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);
}

任何更多的。

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

git reset

如果要删除单个文件

git rm <file>

我建议使用:

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

它会还原你的

git add <your_dir_or_your_file>

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

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重置(见文档)