Git reset


Let’s say you have the following commit history:

$ git log --oneline
e848206 current commit
0923435 previous commit

If you want to undo a commit or go back to a previous state, you can use git reset.

The command has several options:

Soft

Reset the index and keep the changes in the staging area:

$ 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:

$ git reset --mixed HEAD~1
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:

$ git reset --hard HEAD~1
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

Lastly, what if you performed a reset but now you want to undo it?

You can undo your reset 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