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?
- How to rewrite Git history so that all files are in a subdirectory?
- Update a development team with rewritten Git repo history, removing big files
- Git filter-branch with index-filter does not work and remove directories as expected
- Git interactive-rebase across multiple branches
- git : a file in the history without commits on it, how to explain it?
- How to shrink Git repo and better manage large files
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.) --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 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