August 23, 2016
Undo and edit your last commits with git
Sometimes one might get into the unfortunate need to change a git commit. In this post I will show some options to revert or change commits which are not yet pushed to an remote branch.
Undo the last commit
It’s quite easy to undo the last git commit using:
git reset HEAD~
This will remove the very last commit from your local working tree. Your latest changes will still be there and you can just edit them to your needs. When done use
git add .
to add the files into your local working branch again and commit your fix.
Undo any commit
In case you need to edit one specific commit, instead of the last one, git also enables us to do
In this example I have two commits. I need to change the first one, while the last one should stay untouched.
- Pick your commits id from
12345678910111213$ git logcommit 54092b52ac09c32b6712fd6f39e28680bf1507faAuthor: AnonymousDate: Tue Aug 23 16:14:18 2016 +0200good commitcommit 5b5a753329764c9a51935b43961a6598a860f96dAuthor: AnonymousDate: Tue Aug 23 16:13:41 2016 +0200bad commit
In this example the commit we want to edit has the id ‘5b5a753329764c9a51935b43961a6598a860f96d’
- Next do a git rebase:
git rebase --interactive "COMMIT-ID"^
123pick 5b5a753 bad commitpick 54092b5 good commit
This will open an text editor and will show your last commits.
- Search for your bad commit again and then replace the word pick in front with edit
123edit 5b5a753 bad commitpick 54092b5 good commit
If you are using nano as your editor you can close the editor with CTRL + X and then typing ‘y’ to save it.
- Make your changes
- then add the files to the working tree again with
git add .
- re-add them to the commit with
git commit --amend
- Eventually, use
git rebase --continue to merge your changed commit with your other commit.
Now Git will change all subsequent commits and update the mistakes.
If those subsequent commits affect the corrected lines you might need to fix merge conflicts.
Leave a Reply