Throw away local commits in Git
How do you throw away local commits in Git? What commands help you safely discard changes you’ve made locally without affecting the remote repository?
Throwing away local commits in Git is something you might want to do if you realize the changes you made aren’t needed or were done by mistake. But how can you safely discard those commits without messing up the remote repository?
- The easiest way to throw away local commits depends on whether you’ve pushed them or not:
- If you haven’t pushed your commits yet, and want to completely discard them:
Use git reset to move your branch pointer backward.
For example, to remove the last commit but keep the changes staged:
git reset --soft HEAD~1
To remove the last commit and unstage changes (keep them as modified files):
git reset --mixed HEAD~1
To remove the last commit and discard all changes completely:
git reset --hard HEAD~1
Replace 1 with the number of commits you want to discard.
If you’ve already pushed your commits but want to undo them locally and remotely:
You’ll need to use a forced push after resetting:
git reset --hard HEAD~1
git push origin branch-name --force
Be careful with force pushes, especially if others are working on the same branch.
Some quick tips:
- Always double-check which commits you’re discarding using git log.
- If you only want to discard changes in your working directory (not commits), use git checkout -- or git restore .
- Throwing away commits can be a lifesaver when cleaning up your work, but always proceed cautiously to avoid losing important code.