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.

  1. Pick your commits id from git log

    In this example the commit we want to edit has the id ‘5b5a753329764c9a51935b43961a6598a860f96d’
  2. Next do a git rebase: git rebase --interactive "COMMIT-ID"^

    This will open an text editor and will show your last commits.
  3. Search for your bad commit again and then replace the word pick in front with edit

    If you are using nano as your editor you can close the editor with CTRL + X and then typing ‘y’ to save it.
  4. Make your changes
  5. then add the files to the working tree again with git add .
  6. re-add them to the commit with git commit --amend
  7. 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.

Related Posts

Christoph Strauss
Developer at thecodecampus </>

Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

code block

Your email address will not be published.