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?

  • BFG is removing sensitive content everywhere but in the penultimate commit
  • Git: Remove everything except for a certain directory (BFG Repo Cleaner)
  • Undelete specific empty commits after rewriting history with prune-empty
  • git filter-branch does fails when used with more than one file from git ls-files
  • How to amend several commits in Git to change author
  • Git amend/reword (without adding/changing files)
  • Squashing Git commits after merging
  • Remove unused assets from git history
  • 2 Solutions collect form web for “Delete last 2 commits (not pushed) in Git, keeping changes”

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

           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.

    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

    Git Baby is a git and github fan, let's start git clone.