在 git 中,是否有可能取消暂存(未提交)的最后一次更改?假设当前分支中有许多文件,其中一些被暂存,一些未被暂存。假设某个愚蠢的程序员不小心执行了以下操作:
git add -- .
...而不是:
git checkout -- .
这位程序员现在能否通过一些神奇的 git 命令取消暂存他最近的更改?还是说他本来就应该在试验之前进行提交?
在 git 中,是否有可能取消暂存(未提交)的最后一次更改?假设当前分支中有许多文件,其中一些被暂存,一些未被暂存。假设某个愚蠢的程序员不小心执行了以下操作:
git add -- .
...而不是:
git checkout -- .
这位程序员现在能否通过一些神奇的 git 命令取消暂存他最近的更改?还是说他本来就应该在试验之前进行提交?
git reset
命令。这会“取消暂存”你上一次提交之后添加的所有文件。git reset -- <file 1> <file 2> <file n>
命令。git reset -p
命令来取消暂存某些文件中的更改。您无法撤销最近的git add,但是可以撤销自上次提交以来所有的add
操作。在不带提交参数的情况下使用git reset
将重置索引(取消已暂存的更改):
git reset
那么对于问题:
这位程序员现在能否使用某种神奇的git命令取消刚刚添加的更改?
真正的答案是不行,你不能只取消上一次的git add
。
如果我们将问题解释为以下情况:
初始文件:
void foo() {
}
main() {
foo();
}
首先进行更改,然后跟随git add
命令:
void foo(int bar) {
print("$bar");
}
main() {
foo(1337);
}
接着执行 git add
命令的第二个更改:
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 reset
git reset file_name
当使用git时,有以下提示:
如果文件不在仓库中,请使用“git rm --cached <file>...”取消暂存
。它会取消暂存文件,但不会将其删除。如果文件在仓库中,并且您将其添加为修改文件,请使用“git reset HEAD <file>...”取消暂存
。它会保留文件,取消暂存。据我所知,您无法撤消“git add --”操作,但可以按照上述方法取消暂存一系列文件。
git reset
git rm <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 add <your_dir_or_your_file>
返回,同时保持文件不变。
git add
命令添加的更改,特别是对于已经有暂存更改并且需要被撤销的文件。虽然不能说另一个问题与此无关。 - Septagram