Development

Undoing Mistakes in Git Without Losing Work

Which Git command to reach for depending on whether your change is unstaged, staged, committed or already pushed.

SmartCampus Buddy TeamSeptember 5, 20266 min read

Git makes almost any mistake recoverable, provided you pick the right undo for the situation. Start by asking where the change currently lives.

Git's three areas

Changes move from the working tree, to the index (staging area) via git add, to the repository via git commit. Each undo command works on one or more of those areas.

Undo by situation

  • Edited a file, not staged: git restore file discards the edits. This cannot be undone, so be sure.
  • Staged a file by mistake: git restore --staged file unstages it and keeps your edits.
  • Committed too early, not pushed: git reset --soft HEAD~1 removes the commit but keeps the changes staged. --mixed (the default) also unstages them. --hard throws them away.
  • Wrong commit message on the latest commit: git commit --amend, only if it has not been pushed.
  • Already pushed to a shared branch: git revert <commit> creates a new commit that reverses the old one, so nobody's history is rewritten.

Why not just force-push?

Reset followed by a force-push rewrites shared history. Anyone who already pulled the old commits now has a diverged copy. Revert is slower to read in the log but safe for collaborators.

The safety net: reflog

Even after a hard reset, git reflog lists where HEAD used to point for a while, so you can often find the lost commit and recover it with git reset or git checkout -b rescue <sha>.

Key takeaways

  • Identify whether the change is unstaged, staged, committed or pushed before choosing a command.
  • Use revert for shared history and reset for local history.
  • Avoid --hard unless you are sure; check git status first.