删除旧的git提交


88

我对git还是很陌生,想知道是否有可能这样做?

>git log --pretty=oneline --abbrev-commit
2f05aba Added new feature
3371cec Fixed screw up    <-- I want to remove this
daed25c Screw up          <-- and remove this.
e2b2a84 First.                So it's like they never happend.

这可能吗?

Answers:


63

这是可能的git rebase。尝试以下

git rebase -i HEAD~4

然后,按照编辑器中的交互式说明进行操作。在第一步中,您将“压扁”提交。它看起来应该像这样:

pick 2f05aba ... will be preserved
squash 3371cec ... will be squashed with daed25c
squash daed25c ... will be squashed with e2b2a84
pick e2b2a84 .. will contain this and 3371cec and daed25c

在第二步中,您可以编辑提交消息。


25
这不是删除提交而不是压缩提交的问题吗?
理查德

3
@Stony:嗯,您可能也可以删除它们。但是从OP中的提交注释(“拧紧”和“固定拧紧”)中,我认为其中一个正在撤消另一个,并且您也可以将两者压扁。
2013年

85

如果您确实希望删除它们(将它们从历史记录中删除,再也看不到了),则可以

运行变基:

git rebase -i HEAD~4

然后,只需删除(或注释掉)与您希望删除的提交对应的行即可,如下所示:

pick 2f05aba ... #will be preserved
#pick 3371cec ... #will be deleted
#pick daed25c ... #will be deleted
pick e2b2a84 ... #will be preserved

2
我是github的新手,那之后您如何推送更改(当我单击“同步”时,它只是还原我所做的事情)。我想我明白了: git push origin HEAD --force
Nicolas Thery 2014年

@NicolasThery你不要。这就是为什么git push在没有--force的情况下拒绝工作的原因,因为您正在重写历史记录,并且会破坏其他人的存储库。如果您已经推送过,则唯一的选择是执行git revert。哪一个,当您认为这是明智的,因为如果您拉了别人的代码,您会希望他们没有某种历史就能够擦除您的旧提交吗?
愤怒的丹

我认为这在当前的Git仓库中简单起作用,并且不会更改任何上游/任何其他Git节点?
亚历山大·米尔斯

2
@AlexanderMills只要您不推动它,它就不会在上游进行任何更改(如果这样做,您必须添加--force标志,如Angry Dan所说)。
Shathur '17

d或者drop是从历史记录中删除提交的命令。
被遗弃的购物车

5

要完全删除提交,现在有一个drop用于git交互式rebase的新选项。首轮:

git rebase -i HEAD~4

然后替换pickdrop的提交(S)被丢弃:

pick 2f05aba ... #will be preserved
drop 3371cec ... #will be dropped
drop daed25c ... #will be dropped
pick e2b2a84 ... #will be preserved

这适用于Fedora,适用于以下版本:

$ git version
git version 2.21.0

2

当您想在单个哈希下生成合并提交列表时,Squash很有用,但是如果您要进行三个单独的提交并且最终输出看起来像是一次提交,则建议使用Squash fixup

git rebase -i HEAD~4

pick 2f05aba ... will be preserved
fixup 3371cec ... will be merged with daed25c
fixup daed25c ... will be merged with e2b2a84
pick e2b2a84 .. will include 3371cec and daed25c, but only the commit message of e2b2a84

您可以在交互式rebase UI的命令列表中找到更多信息。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.