Removing an Erroneous Git Commit and Cleaning Up History
This article explains how to delete a mistaken Git commit and its record by using interactive rebase, git reset, git revert, and git filter-branch, while highlighting the need for force‑push and the differences between rebase and reset.
After mistakenly committing a private message to a repository, the author demonstrates several ways to remove the erroneous commit and restore the repository to the previous state.
Preparation
A test project is created with sequential files (001‑005) where the fifth commit is the unwanted one.
Solution 1: Interactive git rebase -i
Run git rebase -i HEAD~3 to open an editor with the last three commits, delete the line for the bad commit, save, and then force‑push with git push --force . This rewrites history, removes the commit, and updates the remote repository.
git rebase -i HEAD~3
Successfully rebased and updated refs/heads/master.Force‑pushing overwrites the remote history, so it should be coordinated with the team.
Solution 2: git reset
Using git reset --hard HEAD~1 discards the latest commit entirely. After resetting, a forced push ( git push --force ) is required to sync the remote repository.
git reset --hard HEAD~1Solution 3: git revert
Reverting the bad commit with git revert f3d8db creates a new commit that undoes the changes while preserving history. After reverting, push normally or force‑push if needed.
git revert f3d8dbSolution 4: git filter-branch (advanced)
For a more aggressive rewrite, git filter-branch --commit-filter can change author information or remove commits based on a condition. This rewrites the entire history and should be used with backups and team agreement.
git filter-branch --commit-filter '
if git log --format="%B" -n 1 $GIT_COMMIT | grep -q "异常提交"; then
GIT_AUTHOR_NAME="new baby";
GIT_COMMITTER_NAME="new baby";
git commit-tree "$@";
else
git commit-tree "$@";
fi' -- --allDifference Between git rebase and git reset
git rebase moves a series of commits onto a new base, effectively rewriting history.
git reset moves the HEAD pointer to a previous commit, discarding or unstaging changes.
Both commands are useful for cleaning up commits, but rebase is preferred for reorganizing history, while reset is for discarding recent work.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.