Git reset


This post goes over how to use use git reset to undo a commit or go back to a previous state:

Prerequisites

Let’s say you have the following commit history:

git log --oneline
e848206 current commit
0923435 previous commit

Soft

Reset the index and keep the changes in the staging area with git reset --soft:

git reset --soft HEAD~1 # or replace `HEAD~1` with the commit hash

The HEAD pointer will change to the previous commit:

git log HEAD --oneline --no-walk
0923435 previous commit

And the changes will appear as changes to be commmitted:

git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   file.txt

Mixed

Reset the index and keep the changes in the working tree with git reset --mixed:

git reset --mixed HEAD~1

Output:

Unstaged changes after reset:
M   file.txt

This option is also the default mode.

Similarly, the HEAD pointer will be updated:

git log HEAD --oneline --no-walk
0923435 previous commit

And the changes will appear in the working tree:

git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   file.txt

no changes added to commit (use "git add" and/or "git commit -a")

Hard

Reset the index and discard the changes with git reset --hard:

git reset --hard HEAD~1

Output:

HEAD is now at 0923435 previous commit

As you can see, the changes are not kept:

git status
On branch master
nothing to commit, working tree clean

Final Note

What if you performed a reset but want to undo it?

You can undo it by going back to the previous reference update:

git reset [email protected]{1}

If you’re curious, you can see all your reference logs with reflog:

git reflog


Please support this site and join our Discord!