There are times in development when you may accidentally push the wrong commit to GitHub — maybe it contains sensitive data, an incomplete feature, or simply a mistake. Fortunately, Git provides powerful tools to remove or undo commits, whether they’re local or already pushed to GitHub.
In this guide, we’ll walk through the different ways to remove a commit from GitHub, safely and effectively.
🛑 Important Note Before You Begin
Removing or modifying commits that have already been pushed to GitHub—especially on shared branches like main
—can affect collaborators. Always:
- Communicate with your team before rewriting Git history
- Consider creating a backup branch first
- Be careful with force pushes
✅ Option 1: Remove the Most Recent Commit (Already Pushed)
If you want to remove the last commit that has already been pushed:
🔹 Step 1: Reset the Commit Locally
git reset --hard HEAD~1
This deletes the latest commit and all changes made in it.
🔹 Step 2: Force Push to GitHub
git push origin main --force
Replace
main
with your branch name if different.
✅ Option 2: Revert a Commit (Safer for Shared Branches)
If the commit is already pushed and shared, it’s safer to use git revert
. This creates a new commit that undoes the changes made by a previous commit.
Revert the Last Commit:
git revert HEAD
Or revert a specific commit by hash:
git revert <commit-hash>
Then push the changes:
git push origin main
This is non-destructive and is recommended when working in a team environment.
✅ Option 3: Remove Multiple Commits
To remove the last N commits:
git reset --hard HEAD~N
Then force push:
git push origin branch-name --force
Example: Remove last 3 commits
git reset --hard HEAD~3
git push origin main --force
✅ Option 4: Use Interactive Rebase (Advanced)
If you want to edit, squash, or remove specific commits from the history:
git rebase -i HEAD~n
Replace n
with the number of commits you want to review.
- Change
pick
todrop
to remove a commit - Save and close the editor
- Then force push:
git push origin main --force
⚠️ Undo a Commit Without Losing Changes
If you want to remove the commit but keep the code, use:
git reset --soft HEAD~1
Then you can make further edits or recommit.
✅ Summary
Task | Command |
---|---|
Remove last commit (and changes) | git reset --hard HEAD~1 |
Remove commit but keep changes | git reset --soft HEAD~1 |
Revert pushed commit safely | git revert <commit-hash> |
Delete N last commits | git reset --hard HEAD~N |
Force push after reset | git push origin branch-name --force |
Interactive rebase | git rebase -i HEAD~n |
🚀 Final Thoughts
Removing a commit from GitHub is a powerful capability, but it should be used carefully—especially on branches used by others. Use revert
for safety, reset
for precision, and always consider the implications of rewriting history in collaborative projects.