git 如何删除 Github 和本地的最后 n 次提交?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10153486/
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 13:27:15  来源:igfitidea点击:

How to delete the last n commits on Github and locally?

gitgithubcommit

提问by Ivan Fernandez

I'm trying to delete the last 2 commits from one of my GitHub repositories. I've tried as suggested here: git push -f origin HEAD^^:master. It seems that it works, as the last two commits are removed.

我正在尝试从我的 GitHub 存储库之一中删除最后 2 个提交。我已经按照这里的建议尝试过:git push -f origin HEAD^^:master。似乎它有效,因为最后两个提交被删除了。

Then I deleted them from my local repository with git rebase -i HEAD~2. I remove the lines that are related to those commits, and check with git logthat they are correctly removed.

然后我从我的本地存储库中删除了它们git rebase -i HEAD~2。我删除了与这些提交相关的行,并检查git log它们是否被正确删除。

After that, I make some changes in my local repository, make a new commit, and push to GitHub. The problem is that, in my GitHub account, I have the previous two commits that I've tried to delete.

之后,我在本地存储库中进行了一些更改,进行了新的提交,然后推送到 GitHub。问题是,在我的 GitHub 帐户中,我尝试删除了前两个提交。

I think the problem is in my local repository, because if I clone my Github repository to my local and make some changes here, when I push a new commit those old commits aren't pushed to GitHub.

我认为问题出在我的本地存储库中,因为如果我将 Github 存储库克隆到本地并在此处进行一些更改,那么当我推送新提交时,这些旧提交不会推送到 GitHub。

Any idea?

任何的想法?

回答by KL-7

To remove the last two commits locally I'd suggest using:

要在本地删除最后两个提交,我建议使用:

git reset --hard HEAD^^

Rebase is a completely different operation that won't help you here.

Rebase 是一个完全不同的操作,在这里对您没有帮助。

回答by Dherik

If you want to remove the 2 (two) last commits, there is an easy command to do that:

如果您想删除 2(两)次最后提交,有一个简单的命令可以执行此操作:

git reset --hard HEAD~2

You can change the 2for any number of last commits you want to remove.

您可以更改2要删除的任意数量的最后提交。

And to push this change to remote, you need to do a git pushwith the force(-f) parameter:

并且要将此更改推送到远程,您需要git push使用force( -f) 参数进行操作:

git push -f

However, I don't recommendto do any gitcommand with -for --hardoptions involved if there are new commitson remote (Github) afterthis commits that you want to remove. In that case, always use git revert.

但是,如果在远程(Github)上有新的提交您要删除,我不建议执行任何涉及的git命令-f--hard选项。在这种情况下,请始终使用.git revert

回答by Sial01

The following works for me

以下对我有用

git reset HEAD~n

It removes the last ncommits from local repo, as HEAD^removes only one. If you need to remove these changes from remote, you might need to force push as you will be behind remote.

n从本地存储库中删除最后一个提交,因为HEAD^只删除一个。如果您需要从远程删除这些更改,您可能需要强制推送,因为您将落后于远程。

git push -f origin <branch>