How to revert two commits back and commit only good stuff?
Revert changes in a new Commit
If you want to completely undo the commits and delete them, use rebase
or reset
like other answers suggest.
But sometimes, you can't modify git history (for example after pushing to a protected branch on remote). In that case, your best bet is git revert
:
git revert --no-commit HEAD~1^..HEAD
This will revert all changes in the last two commits (from HEAD
to HEAD~1
). You can make sure everything looks good by checking the status or diff and commit the revert:
git status # or git diff
git commit -m "Reverted the last two commits"
First, git reset HEAD~2
to discard the top two commits, while leaving your working tree exactly as it is.
Then, simply create a new commit with what you want (e.g., with git add
s and then git commit
).
See Reset Demystified by Scott Chacon for the details on the often confusing git reset
comamnd.
You can do a git rebase -i HEAD~2
and then use the interface to discard the "bad commits" that are there since then and clean up your history. This however alters the project history and if you've already pushed (and others pulled) your changes, there are some social issues to work out.
The other option is to git revert
those changes. Then 2 new commits will get added to the history that makes the fact that you don't want these two commits explicit in the project history. Less clean but easier to work with.