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
- The Git Command Finder
- A terminal in your repository
Steps
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.Only the message is wrong
Search for “change the last commit message”.
git commit --amendlets you edit the message, and also adds anything you have staged since.Undo it but keep the changes
Search “undo last commit”.
git reset --soft HEAD~1removes 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"Throw it away completely
git reset --hard HEAD~1deletes the commit and its changes. The tool marks it Can lose work. If you regret it,git reflogstill shows the commit for a while.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.
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
--hardalso discards uncommitted changes in your working files. Checkgit statusfirst.
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.