How to Undo Commit and Discard Changes in Git
Use
git reset --hard HEAD~1 to undo the last commit and discard all changes in it. This command moves your branch back one commit and deletes any changes from your working directory and staging area.Syntax
The main command to undo a commit and discard changes is git reset --hard HEAD~1.
git reset: Moves the current branch pointer.--hard: Resets the staging area and working directory to match the commit.HEAD~1: Refers to the commit before the current one (one commit back).
bash
git reset --hard HEAD~1Example
This example shows how to undo the last commit and remove all changes from your files.
bash
$ git log --oneline -1 abc1234 Add new feature $ git reset --hard HEAD~1 HEAD is now at 9f8e7d6 Fix typo $ git log --oneline -1 9f8e7d6 Fix typo
Output
HEAD is now at 9f8e7d6 Fix typo
Common Pitfalls
Be careful: git reset --hard deletes changes permanently from your working directory and staging area. If you want to keep changes but undo the commit, use git reset --soft HEAD~1 instead.
Also, if you already pushed the commit to a shared repository, undoing it locally can cause conflicts. In that case, coordinate with your team or use git revert.
bash
Wrong (loses uncommitted changes): git reset --hard HEAD~1 Right (keeps changes staged): git reset --soft HEAD~1
Quick Reference
| Command | Description |
|---|---|
| git reset --hard HEAD~1 | Undo last commit and discard all changes |
| git reset --soft HEAD~1 | Undo last commit but keep changes staged |
| git revert | Create a new commit that undoes a previous commit |
| git status | Check current changes and commit status |
Key Takeaways
Use
git reset --hard HEAD~1 to undo the last commit and discard all changes safely.Avoid
--hard if you want to keep your changes; use --soft instead.Undoing commits that are already pushed requires careful coordination or using
git revert.Always check your current status with
git status before undoing commits.Remember that
git reset --hard permanently deletes uncommitted changes.