Un-commit in Git

I just accidentally made a commit in git that I didn’t want – I’d made several changes at once and wanted to commit them separately. Instead I did one big commit so I wanted to get back to a state where I had the uncommitted changes. The methods of undoing a commit (git reset and git revert) dont cut it here, as they just take you back to the previous commit, and lose the changes you made. Here’s what I came up with:

git show > ~/uncommit.patch # Take the commit I just made and store the differences in a patch
git reset --hard HEAD^ # Reset to the previous commit
patch -p1 < ~/uncommit.patch # Re-apply the changes

If you've got some changes that aren't committed yet that you still want to keep, you'll want to do make a second patch from the output of git diff before resetting.

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *