user1960364
user1960364

Reputation: 2009

Delete last 2 commits (not pushed) in Git, keeping changes

I'm trying to delete, not revert, the last 2 commits on the develop branch of my Git repo. The commits have not been pushed.

How would I go about doing this without losing the changes?

Upvotes: 6

Views: 1787

Answers (2)

gravetii
gravetii

Reputation: 9654

I think what you want to do is squash the last 2 commits. You can do this by interactive rebasing.

git rebase -i HEAD~3

and then mark the last 2 commits as f (fixup) or s (squash) accordingly.

Here's a tutorial on interactive rebasing

Upvotes: 1

martin
martin

Reputation: 3249

On the develop branch, you would use

git reset HEAD~2

This will reset the HEAD pointer to the commit 2 before your current without losing the changes.

Here is the excerpt from the help:

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.

Thus, it only resets the index, and not the tree. The changes of your files are kept and not added to the index. If you want that, use the --soft flag:

   --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.

Upvotes: 11

Related Questions