如何撤消上次 git add/commit?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4498281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 09:40:33  来源:igfitidea点击:

How can I undo my last git add/commit?

gitrepositorycommitundo

提问by dave

I edited a file and did:

我编辑了一个文件并做了:

git add file.py
git commit -m 'fixed bug'

I then edited another file and performed a minor bug fix. I don't want two commits, one after the other, showing 'bug fix'. I want one commit with 'bug fixes'.

然后我编辑了另一个文件并执行了一个小错误修复。我不想要两个提交,一个接一个,显示“错误修复”。我想要一个带有“错误修复”的提交。

How can I undo the last add/commit and change the first commit message?

如何撤消最后一次添加/提交并更改第一条提交消息?

I was looking at the git reset, git revert, git undocommands but I don't want to screw up my repo with a guess

我正在查看git reset, git revert,git undo命令,但我不想用猜测来搞砸我的回购

EDIT: Found out how to do it: http://www.gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

编辑:找出如何去做:http: //www.gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html

回答by Gauthier

If you already commited your second change, reset it first:

如果您已经提交了第二个更改,请先重置它:

git reset HEAD^

Now your HEADis at the first commit, and the content of your local files is unchanged.

现在您HEAD处于第一次提交,并且本地文件的内容没有改变。

git add <the file(s) for the second bug fix>
git commit --amend -m'bug fixes'

If all tracked and changed file are to be included for the second bug fix, you can run this instead, as usual:

如果所有跟踪和更改的文件都包含在第二个错误修复中,您可以像往常一样运行它:

git commit -a --amend

Amending the commit is exactly this:

修改提交正是这样:

  • adds the changes in index to the previous commit (therefore the need for git add, or -a)
  • allows you to change your commit message
  • 将 index 中的更改添加到先前的提交中(因此需要git add, 或-a
  • 允许您更改提交消息

Be careful, though: if you have distributed the first commit, other people's repo will get strange. You should not change a commit that someone else has fetched.

不过要小心:如果你已经分发了第一个提交,其他人的 repo 会变得奇怪。您不应更改其他人已获取的提交。



You could also probably use git merge --squash, which feels more logical but not necessarily easier. Use it to merge a branch containing your two commits, unto the previous commit.

您也可以使用git merge --squash,这感觉更合乎逻辑,但不一定更容易。使用它将包含您的两个提交的分支合并到前一个提交。

Squashing works with git rebaseas well.

挤压也适用git rebase