How do you undo the last commit in Git?

Keep or discard your changes while rolling back the most recent commit using git reset or git revert.

GitVersion Control

Overview

Undoing a commit is one of the most common Git operations. The right command depends on whether the commit has already been pushed and whether you want to keep your changes. `git reset` rewrites history (safe for local-only commits). `git revert` creates a new commit that undoes the changes (safe for shared branches).

Key Points

  • •`git reset --soft HEAD~1` undoes the commit but keeps your changes staged.
  • •`git reset --mixed HEAD~1` (default) undoes the commit and unstages changes, but keeps files.
  • •`git reset --hard HEAD~1` discards the commit AND all file changes permanently.
  • •`git revert HEAD` creates a new "undo" commit this is the safe option for pushed branches.
  • •Never use `--hard` unless you are certain you want to lose those changes.

Examples

Undo last commit, keep changes staged (soft reset)

bash
git reset --soft HEAD~1

Your files are unchanged; the commit is removed but the changes stay in the staging area.

Undo last commit, keep files but unstage (mixed reset default)

bash
git reset HEAD~1
# same as: git reset --mixed HEAD~1

Files are unchanged but no longer staged. You can edit and re-commit.

Undo last commit AND discard all changes (hard reset)

bash
git reset --hard HEAD~1

DANGER: file changes are permanently lost. Use only on local commits.

Safely undo a pushed commit with git revert

bash
git revert HEAD
# this creates a new commit that undoes the last one
git push

Safe for shared branches history is preserved; a new "revert" commit is added.

Pro Tip

If the commit was already pushed to a shared branch, always use `git revert` instead of `git reset`. Rewriting pushed history forces all collaborators to re-sync and can cause serious problems.