How To Undo The Last Local Commit In Git?

Learn how to undo last git commit in your local branch

  • By Daniyal Hamid
  • May 25, 2019
  • Comments
In This Article

To undo your last local commit on the current branch, you can simply reset the HEAD on the current branch.

Before we dive into the "how-to", perhaps it's important to understand what the "HEAD" refers to. "HEAD" is simply a reference to a commit on the branch you're on. Normally it's written as HEAD~N where "N" is the number of commits you wish to refer back to (for example HEAD~2 refers to the commit one previous to the latest one). By default the value of HEAD~ is 1 (i.e. the current/latest commit on the current branch) so there's no need to explicitly write HEAD~1.

Undo The Last Commit And Unstage Changes

git reset HEAD~

# or, alternatively:
git reset --mixed HEAD~

To see all the unstaged files you had previously committed you can simply do git status.

What Does It Do?

Doing a mixed reset of HEAD~ will:

  1. Undo your last local commit in the branch you're in, and;
  2. Leave the changes you committed unstaged (like how the files are before doing git add).

Remember, you will need to git add your files again before doing a new commit.

When Is It Useful?

When you want to undo the last commit but keep all your changes so you can continue editing before you do a new commit.

Undo The Last Commit And Keep Changes Staged

git reset --soft HEAD~
What Does It Do?

Doing a soft reset of HEAD~ will:

  1. Undo your last local commit in the branch you're in, and;
  2. Keep the changes you committed staged (like how the files are right after git add but before a git commit).
When Is It Useful?

When you want to:

  • Add more changes to the previous commit;
  • Change the commit message;
  • Squash/combine earlier commits together into one single commit. For example, the following command squashes together last three commits into a single one:
    git reset --soft HEAD~3 && git commit -m "Squashed commit"
    

Undo The Last Commit And Discard Changes

git reset --hard HEAD~

Be cautious of doing a hard reset if you have uncommitted work. If this is the case, then you should stash your uncommitted work prior to doing a hard reset and add it back right after. For example:

git stash
git reset --hard HEAD~
git stash pop
What Does It Do?

Doing a hard reset of HEAD~ will:

  1. Reset files to the state one before the latest commit, discarding all the changes you made to the files in the latest commit;
  2. Reset HEAD to the commit one before the latest one.
When Is It Useful?

When you want to undo the last commit and you don't care about any changes you made to the files in the commit and would like to discard them all.


We hope you found this quick tutorial useful. If you have something to add to it, please let us know in the comments section below.