How to Undo a Pushed Git Commit? A Step‑by‑Step Interview Guide
This article walks through four practical ways to revert code that has already been pushed to a remote Git repository—including manual diff removal, using git revert, creating a new branch, and resetting the current branch with hard, mixed, or keep options—plus tips on force‑pushing and branch protection.
1. Manual comparison (not recommended)
If you have only a few erroneous lines, you can compare the target commit with the current state, manually delete the unwanted code, and commit the cleaned version. This approach works for simple changes but becomes cumbersome for complex codebases or configuration files.
2. git revert (recommended)
When you have a wrong commit that has already been pushed, right‑click the offending commit in your IDE (e.g., IntelliJ IDEA) and select Revert . Git automatically creates a new revert commit that undoes the changes introduced by the original commit while preserving history.
After the revert commit is created, simply push it to the remote repository to complete the rollback.
3. Create a new branch (useful for many commits)
If you need to roll back dozens or hundreds of commits, create a new branch at the commit you want to keep. Right‑click the desired commit and choose New Branch . This preserves the original history on the old branch while giving you a clean branch to continue development.
4. Reset the current branch to a specific commit (use with caution)
Open the reset dialog and select the desired commit. Choose one of the following reset modes:
Soft : Keeps your working directory and index unchanged; only the HEAD moves.
Mixed : Resets the index but leaves the working directory untouched.
Hard : Resets both index and working directory to the selected commit, discarding all local changes.
Keep : Resets to the commit but preserves uncommitted local changes.
After resetting, the erroneous commits disappear locally, but the remote still contains them. To synchronize the remote, perform a Force Push . Note that force‑pushing is prohibited on protected branches; ensure the target branch is not protected before proceeding.
Warning: Using reset with the hard or keep options can lead to data loss if you have uncommitted work. Always verify the selected mode and consider creating a backup branch first.
These steps were demonstrated using IntelliJ IDEA 2023; command‑line equivalents are also available for those who prefer Git CLI.
Java Architect Handbook
Focused on Java interview questions and practical article sharing, covering algorithms, databases, Spring Boot, microservices, high concurrency, JVM, Docker containers, and ELK-related knowledge. Looking forward to progressing together with you.
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.
