Skip to content
Tutorials Center
My learning

Topics

Git Reference ยท Concepts

Undoing things in Git

Choose the right Git undo: restore for files, reset for local commits, revert for shared history, amend for the last commit and reflog to recover.

"Undo" means different things in Git depending on what you want to take back and whether others have seen it. Pick the tool by answering two questions: which of the three states is involved (working tree, staged, committed), and has the commit been pushed?

Situation Tool
Discard edits to a file git restore file
Unstage a file git restore --staged file
Fix the last commit (message or content) git commit --amend
Throw away local, unpushed commits git reset --hard <commit>
Uncommit but keep the changes git reset --soft or --mixed <commit>
Undo a commit already shared git revert <commit>
Get back something "lost" git reflog, then git reset or git branch
Abandon an unfinished merge, rebase or cherry-pick git merge --abort, git rebase --abort, git cherry-pick --abort
Remove untracked files git clean -n, then git clean -f

Try it

Bash Undoing at each level

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Bash Revert shared history and recover with the reflog

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Usage notes

  • Local versus shared. Anything you have not pushed can be rewritten freely (amend, reset, rebase). Anything others may have pulled should be undone with git revert, which adds history instead of removing it.
  • Danger list. The commands that really destroy uncommitted data are git restore <file> (working-tree edits), git reset --hard, git checkout -- <file> and git clean -f. Dry-run first: git clean -n.
  • Committed means recoverable. Once data is in a commit, the reflog keeps it for weeks even after a reset. Once it is staged, the blob exists (git fsck --lost-found). Edits that were never staged cannot be recovered by Git.
  • Reverting a merge needs -m 1 to say which parent to keep. Reverting it also means that a later re-merge of the same branch brings nothing in until you revert the revert.
  • Undo a push by reverting and pushing, or, on a private branch, git push --force-with-lease after a reset. See Rewriting history safely.
  • Undo an amend or rebase with git reset --hard ORIG_HEAD right after, or via the reflog later.
  • Single file from the past: git restore --source=<commit> file brings back an old version without moving any branch.