How to Undo a Pushed Commit in Git: Manual Comparison, Revert, Branch, and Reset Techniques
This guide explains several practical methods—including manual comparison, git revert, creating a new branch, and various git reset options—to safely roll back code that has already been pushed to a remote repository, while also covering force‑push considerations.
1. Basic Manual Operation (Not Recommended)
For small mistakes you can compare the erroneous commit with the target commit, manually delete the unwanted changes, and use the IDE's "Compare Versions" feature to remove the code, though this becomes cumbersome for complex changes.
2. git Revert Commit (Recommended)
Right‑click the erroneous commit and select Revert ; Git creates a new revert commit that undoes the changes, preserving history. Push the revert commit to the remote to complete the rollback.
The revert command is safe but only reverts one push at a time, which can be inefficient for many consecutive bad commits.
3. Create a New Branch (Recommended for Large Rollbacks)
When needing to revert many commits, right‑click the desired commit and choose New Branch . This creates a branch at the target state, keeping the original history intact while allowing you to work from the earlier point without generating numerous revert records.
4. Reset Current Branch to a Specific Commit (Use with Caution)
Use git reset with one of the following options:
Soft : Keeps working directory changes; only moves the HEAD.
Mixed : Resets the index but leaves working files unchanged.
Hard : Discards all changes and matches the working directory to the selected commit.
Keep : Resets to the commit but preserves uncommitted local changes.
After resetting, force‑push the branch to update the remote repository, noting that protected branches may reject a force push.
These methods provide flexible ways to undo pushed code, each with trade‑offs between safety, history preservation, and convenience.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.