在Git中删除最后2个提交(未推送),保留更改。

4

我想删除 Git 仓库 develop 分支上的最新两个提交(不是“还原”)。这些提交尚未推送到远程分支。

请问我该如何处理,以免丢失更改内容?


1
你想删除提交记录但又不想丢失它们吗?你希望将它们放在哪里? - Chris Martin
2个回答

9

在develop分支上,您需要使用

git reset HEAD~2

这将重置HEAD指针到当前提交前的第2个,而不会丢失更改。
以下是从帮助中提取的摘录:
git reset [-q] [<tree-ish>] [--] <paths>...
       This form resets the index entries for all <paths> to their state
       at <tree-ish>. (It does not affect the working tree, nor the
       current branch.)

   --mixed
       Resets the index but not the working tree (i.e., the changed
       files are preserved but not marked for commit) and reports what
       has not been updated. This is the default action.

因此,它只重置索引,而不是树。您的文件更改将被保留,并且不会添加到索引中。如果您想要这样做,请使用--soft标志:
   --soft
       Does not touch the index file nor the working tree at all (but
       resets the head to <commit>, just like all modes do). This
       leaves all your changed files "Changes to be committed", as git
       status would put it.

@martin,我只是好奇,你需要 --soft 标志吗? - mTorres
不知道为什么被踩了。顺便说一下,你可以添加一些解释来赢回投票。 - Rohit Jain
1
@mTorres 使用 --soft 选项,更改将会被暂存,而在这种情况下,更改将作为本地修改。根据 OP 的要求,两者都可以使用。 - Rohit Jain
@mTorres 默认模式是 --mixed - Chris Martin
谢谢大家的解释 :-) - mTorres
这正是我想要的,感谢您的快速回复和解释! - user1960364

1
我认为你想要做的是压缩最后两个提交。您可以通过交互式重新基础操作来实现此目的。 git rebase -i HEAD~3 然后相应地将最后2个提交标记为f(修复)或s(压缩)。
这里有一个交互式重新基础操作的教程。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接