Sometimes you may want to delete a commit from your Git history—whether it’s to remove a mistaken change or clean up your project’s commit log. Git provides multiple ways to handle this, depending on whether the commit is local or already pushed.
This guide covers the safest and most common methods to delete commits in Git.
⚠️ Important Note
- Deleting commits rewrites history, which can affect collaborators if the commits are already pushed to a shared repository.
- Always communicate with your team before rewriting published history.
- Consider backing up your branch before proceeding.
✅ Method 1: Delete the Most Recent Commit (Local)
If the commit you want to delete is the latest one and has NOT been pushed, you can use:
git reset --hard HEAD~1
This moves your current branch pointer back by one commit, effectively deleting the latest commit and discarding any changes.
- To keep the changes unstaged (in your working directory), use:
git reset --soft HEAD~1
✅ Method 2: Delete a Specific Commit Using Interactive Rebase
To delete a commit that is not the latest:
- Run an interactive rebase starting from a few commits back:
git rebase -i HEAD~N
Replace N
with the number of commits you want to look back (e.g., 5).
- An editor opens showing the commits. Each line starts with
pick
. - Find the commit you want to delete and delete its entire line or replace
pick
withdrop
. - Save and close the editor.
Git will reapply the remaining commits and remove the dropped one.
✅ Method 3: Delete a Commit That Has Been Pushed (Force Push Required)
If the commit is already pushed and you want to remove it from the remote repository:
- Use interactive rebase as in Method 2 to remove the commit locally.
- Force push the changes to the remote:
git push origin branch-name --force
Warning: Force pushing can overwrite others’ work. Coordinate carefully with your team.
🧩 Summary of Commands
Task | Command |
---|---|
Delete latest commit (discard changes) | git reset --hard HEAD~1 |
Delete latest commit (keep changes) | git reset --soft HEAD~1 |
Interactive rebase to delete commit | git rebase -i HEAD~N (then delete/drop line) |
Force push after rewriting history | git push origin branch-name --force |
📌 Final Tips
- Use
git log
to review commit history before deleting. - Avoid rewriting history on shared branches unless necessary.
- Create a backup branch before complex history edits:
git branch backup-branch