| English | 中文 |
Before undoing in Git, first determine the state of the changes.
Only three questions matter:
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
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
For public commits, prioritize using:
git revert <commit-sha>
This will add a reverse commit, keeping history clear without breaking collaborators’ local branches.
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