How to undo the last git commit?

The main benefit of using a version control system like git is you can undo or redo your last or specific local or remote commits if already pushed.

Git provides you with four levels of stages where you can undo or redo changes.

  • Working tree – This is your local git directory (before changes are staged)
  • Staging area – This is the in-between state of working tree and local repository (after changes are staged but before commit)
  • Local repo – This is your local git repository (after changes are committed)
  • Remote repo – This is your central remote repository (after changes are pushed)

Note: Git also has tagging feature which keeps a version of your changes.

Warning: The command given below are for demo only and do not execute them blindly particularly if you are working with a remote repository.

Working tree:

Remove changes in git working tree:

Add changes from git working tree to the staging area:

Staging area:

Undo changes from git staging area (keeping your changes in the working tree):

Undo changes from git staging area (discarding all changes):

Redo changes from git staging area to the local repository:

Local repository:

Undo git commits from a local repository (keeping your changes in staging area):

Undo git commits from a local repository (keeping your changes in the working tree):

Undo commits from a local repository (discarding your changes):

Redo commits from local repository to remote repository:

Remote repository:

Undo last git commit in git remote repository:

Undo last git commit message:

Undo last git commit message in local repository:

Undo last git commit message in a remote repository:

Undo a git tag in remote and local repository

Leave a Reply