删除Git中的最后2次提交(未推送),保留更改

时间:2014-08-19 07:57:31

标签: git commit git-rewrite-history

我试图删除,而不是revert,我的Git仓库的开发分支上的最后两次提交。提交尚未推出。

如何在不丢失更改的情况下执行此操作?

2 个答案:

答案 0 :(得分:7)

在开发分支上,您将使用

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.

答案 1 :(得分:1)

我认为你想做的是压缩最后两次提交。您可以通过交互式变基来实现这一目标。

git rebase -i HEAD~3

然后将最后两次提交标记为f(fixup)或s(壁球)。

这是interactive rebasing

的教程