Git Command Finder & Cheat Sheet · Tutorial

How to undo the last git commit safely

6 min readbeginnerUpdated

You just committed something wrong: the wrong files, a bad message, or a change you didn’t mean. The right fix depends on whether you pushed and whether you want to keep the changes. This tutorial walks through each case.

What you need

Steps

  1. Check whether you pushed

    Run git status. If it says your branch is ahead of origin, the commit is only local and you can rewrite it freely. If it is up to date, the commit is already on the remote.

  2. Only the message is wrong

    Search for “change the last commit message”. git commit --amend lets you edit the message, and also adds anything you have staged since.

  3. Undo it but keep the changes

    Search “undo last commit”. git reset --soft HEAD~1 removes the commit and keeps everything staged, so you can fix it and commit again.

    git reset --soft HEAD~1
    git restore --staged secrets.txt   # unstage the file you didn't mean to commit
    git commit -m "Add login form"
  4. Throw it away completely

    git reset --hard HEAD~1 deletes the commit and its changes. The tool marks it Can lose work. If you regret it, git reflog still shows the commit for a while.

  5. It was already pushed

    Use git revert <commit> instead. It adds a new commit that undoes the old one, so teammates who already pulled don’t get a broken history.

Try it yourself

Opens the Git Command Finder & Cheat Sheet with this tutorial's sample loaded.

Try it now

Common mistakes

Resetting a shared branch
Resetting and force pushing main makes everyone else’s copy disagree with the remote. Revert instead.
Using --hard when you meant --soft
--hard also discards uncommitted changes in your working files. Check git status first.

Next steps

Go back to the Git Command Finder & Cheat Sheet, or keep going with one of these:

FAQ

What if I committed a password?

Remove it with the steps above, but also change the password. If it was pushed, assume it is exposed even after undoing the commit.