How can I undo my last git commit?

Posted November 11, 2016 96.3k views

You run git commit only to realize you forgot to add a file or that you made a mistake. We all do it, but we can never remember how to undo it! What is the command to undo a git commit?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer

To undo your last commit and leave the previously committed changes unstaged, use the command:

  • git reset HEAD~

Personally, I like to keep this aliased to git uncommit for quick reference. To do so, add this to your git configuration:

    uncommit = "reset HEAD~"

If you’d like to undo the commit but leave the changes staged, run:

  • git reset --soft HEAD~

If you simply want to redo the commit message, there is no need to rest. You can change the message using:

  • git commit --amend

This can also be used to add changes to the previous commit. For example, to add a file that you forgot to include, run:

  • git add forgotten_file
  • git commit --amend

You’ll be given the opportunity to modify the commit message and the newly added file will be included.

To completely remove all traces of the last commit, nuke it from orbit with:

  • git reset --hard HEAD~1

To revert to a specific previous commit, losing all history between, use:

  • git reset --hard a731962
  • Great one. =)

    Maybe beside that it would add that you’re able to merge multiple commits.

    If you run:

    • git rebase -i origin/master

    It’ll show you text editor with list of commits:

    git rebase - interactive
    pick e2f6b1a README updates
    pick d12a7b2 updated dependencies
    pick f6af3e1 implemented version check

    Now check all pick-s to squash expect first one (highlighted at example):

    git rebase - interactive - after changes
    pick e2f6b1a README updates
    squash d12a7b2 updated dependencies
    squash f6af3e1 implemented version check

    Close editor. You could be asked to add new commit message for it.
    After push you should be good to go.
    This one can be useful too. :D