How to undo a Git commit that was not pushed 3


To undo a Git commit that was not pushed, you are given a few major options:

  1. Undo the commit but keep all changes staged
  2. Undo the commit and unstage the changes
  3. Undo the commit and lose all changes

Method 1: Undo commit and keep all files staged

In case you just want to undo the commit and change nothing more, you can use

git reset --soft HEAD~;

This is most often used to make a few changes to your latest commit and/or fix your commit message. Leaves working tree as it was before reset.
soft does not touch the index file or the working tree at all (but resets the head to the previous commit). This leaves all your changed files Changes to be committed, as git status would put it.

Method 2: Undo commit and unstage all files

In case you want to undo the last commit and unstage all the files you can use the following

git reset HEAD~;

or

git reset --mixed HEAD~;

mixed will reset the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

Method 3: Undo the commit and completely remove all changes

The following method will undo the commit and revert all changes so that your state is exactly as it was before you started making changes.

git reset --hard HEAD~;

hard resets the index and working tree. Any changes to tracked files in the working tree since the previous commit are discarded.

 

Note: In case you just want to rewrite the commit message, you could use git –amend instead.

This post is also available in: Greek


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 thoughts on “How to undo a Git commit that was not pushed

  • Software Developer Guy

    Hey George, this was a great post I appreciate you sharing. I had one follow up question which I was not 100% on. When using method 2 – undoing the commit but “unstaging” all files. Would you be able to help me further understand what it means to unstage files in this context? I am a a bit new and am having trouble wrapping my head around some of these concepts.

    Thanks!

    – Eric

    • George

      Hello Eric,

      In the process of creating a commit, you normally specify the files to be added to the commit by using the git add command. All files that are added to a commit before executing the git commit command are called staged.

      When you use method 1, it will undo the commit but keep the files staged, this way you can re-create your commit in as few steps as possible (it is possible to just execute git commit with a new message immediately and create a new commit).
      Using method 2 on the other hand, not only will it revert the commit but it will also clear the stage. This means that if you want to create a new commit, then you will have to specify from scratch which files should be added to the commit using git add.