asb
By:
asb

How can I undo my last git commit?

November 11, 2016 121 views
Git

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?

1 Answer
asb MOD November 11, 2016
Accepted 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:

~/.gitconfig
[alias]
    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

Have another answer? Share your knowledge.