Git makes it easy to undo your most recent local commits (commits that haven’t been pushed yet). Below are the safest and most common ways to do it.
1. Undo the Last Commit (Keep Changes Staged)
If you want to undo the last commit but keep your changes staged:
git reset --soft HEAD~1
2. Undo the Last Commit (Keep Changes Unstaged)
To undo the commit but keep the changes in your working directory:
git reset --mixed HEAD~1
or simply:
git reset HEAD~1
3. Completely Remove the Last Commit
If you want to remove the commit and discard all changes:
git reset --hard HEAD~1
⚠️ This permanently deletes your changes.
Use only when you are absolutely sure.
4. Undo Multiple Local Commits
To undo the last N commits, replace N with the number of commits:
git reset --soft HEAD~N
Example (undo last 3 commits):
git reset --soft HEAD~3
Use these commands only for local commits.
If the commit is already pushed to a remote repository, prefer git revert to avoid breaking shared history.
Top comments (0)