How to Delete a Git Commit History Using git revert and git reset
This article explains why you might need to remove a Git commit from history and provides step‑by‑step instructions for using git revert, git reset (soft, mixed, hard), and force‑push to permanently delete unwanted commits while highlighting the risks involved.
Why Delete Commit History
A teammate pushed a mistaken commit to a shared remote repository, and the author needs to erase that history to avoid exposing the error.
Using git revert to Undo Commits
git revert creates a new commit that reverses the changes of a specified commit, preserving the original history.
Syntax
git revert <commit-hash> git revert <commit-hash1> <commit-hash2> ... git revert HEAD git revert <commit-hash1>^..<commit-hash2>After running the command, Git opens an editor (e.g., Vim) for the revert commit message; the user saves and exits, then pushes the new commit.
Using git reset to Remove Commits Completely
git reset moves the HEAD pointer and can optionally modify the index and working tree, allowing you to discard commits without creating new ones.
Common Forms
git reset --soft HEAD~1Moves HEAD back one commit while keeping changes staged.
git reset HEAD~1Moves HEAD back one commit, unstaging changes but keeping them in the working directory.
git reset --hard HEAD~1Moves HEAD back one commit and discards all changes.
git reset --hard <commit-hash>Moves HEAD to a specific commit, discarding later work.
To delete the unwanted commits from the remote repository, force‑push the cleaned local branch:
git push --forceor the explicit form:
git push origin <branch-name> --forceImportant Warning
Using --force overwrites the remote history, which is dangerous; ensure the local state is correct and coordinate with teammates before doing so.
Summary
git reset can rewrite history by moving the branch pointer, while git revert preserves history by adding a new commit that undoes changes; the article demonstrates how to combine git reset with git push --force to permanently remove erroneous commits from a remote repository.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.