my-git

Undo Anything

English 中文

Before undoing in Git, first determine the state of the changes.

Only three questions matter:

  1. Have the changes been committed?
  2. Has the commit been pushed?
  3. Has anyone continued development based on it?

Local Uncommitted Changes

Discard working tree changes of a file:

git restore <file>

Unstage:

git restore --staged <file>

Discard working tree changes of all tracked files:

git restore .

Check before executing:

git status
git diff

Committed but Not Pushed

Amend the last commit:

git commit --amend

Undo the last commit, but keep changes in the staging area:

git reset --soft HEAD~1

Undo the last commit, and keep changes in the working tree:

git reset HEAD~1

Pushed Public Commits

For public commits, prioritize using:

git revert <commit-sha>

This will add a reverse commit, keeping history clear without breaking collaborators’ local branches.

High-Risk Commands

git reset --hard
git push --force
git clean -fd

Before executing these commands, confirm there are no changes you need to preserve.

Create a backup branch first:

git branch backup-before-undo

Further Reading