Undo a Git Commit: Two Questions Before You Type Anything
"How do I undo a commit?" has four correct answers and three wrong ones, and the difference is not the command — it is two questions you ask before typing anything: Where is the change? Working tree, staged, committed, or committed and pushed ? Has anyone else got it? Answer those and the command picks itself. Below is each situation, run in a disposable repository (git 2.43.0) with real output,…
When undoing a Git commit, there are four correct answers and three wrong approaches. To determine the right command, you must first answer two key questions: Where is the change? (working tree, staged, committed, or committed and pushed?) and Has anyone else got it?
1. If you edited a file and want to remove the change, the file is in your working tree. Use git restore <file> to revert the change. Example: echo oops config.txt → git status --short → M config.txt → git restore config.txt → Empty output.
2. If you staged something too early and don't want it in the next commit, the change is in the index. Use git restore --staged <file> to unstage the change without touching the file. Example: echo staged config.txt → git add config.txt → git status --short → M config.txt → git restore --staged config.txt → M config.txt again.
3. If you committed too early and the changes are not pushed, the commit exists in your branch. Use git reset --soft HEAD~1 to move the branch pointer back without changing the staged or working tree. This keeps the changes staged for a recommit. Example: git reset --soft HEAD~1 → git status --short → git log --oneline → M config.txt 76ca1c4.
4. If the commit has been pushed and others have pulled it, you cannot simply rewrite history. Instead, use git revert HEAD --no-edit to create a new commit that undoes the changes. Example: git revert HEAD --no-edit → git log --oneline | head -2 → Revert Add line4 6a6f2b6.
Avoid using git reset --hard, as it discards all uncommitted changes and cannot be used after pushing. If you must discard everything, use git reset --hard HEAD forcefully with caution, as it cannot be undone.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.