How to Fix Mistaken Git Commits: Amend, Reset, and Revert Explained
This guide shows developers how to correct erroneous Git commits by using amend for message or author changes, reset (soft, mixed, hard, keep) to undo commits, and revert to create a new corrective commit, with practical code examples for each scenario.
1. Introduction
Everyone makes mistakes when coding; you may accidentally commit the wrong code or write a poor commit message. This article explains how to fix such Git commit errors.
2. What to Do When a Commit Is Wrong
Scenario 1
If you have already run git commit but the commit message is unsatisfactory, you can amend it:
git commit --amend -m "New commit message"Scenario 2
You committed four files instead of the intended five. Use git commit --amend to add the missing file without creating a new commit:
git add forgotten_file
git commit --amend --no-editScenario 3
When the author information is incorrect, amend the commit with the proper author:
git commit --amend --author "felord<[email protected]>"Prefer fixing these errors locally before pushing. The amend command rewrites history and can make the log confusing; git commit -am is not a shortcut for git commit --amend .
Scenario 4
To undo the most recent commit (local or remote), use git reset. For example, to move the latest commit back to the previous one:
git reset --soft 8e7089f62ad8588f5710f23d6a8ce1158490032b git resetsupports four modes: soft, mixed, hard, and keep.
The git revert command also creates a new commit that undoes changes, but unlike git reset it requires a commit message.
Scenario 5
If the changes have already been pushed and you need to revert a specific file, view its history, check out the desired commit for that file, and recommit:
# View file history
git log <filename>
# Roll back to a specific commit
git checkout <commitId> <filename>
# Commit the reverted file
git commit -m 'Revert specific file changes'
# Push the fix
git push3. Summary
These commands are essential for correcting commit mistakes. Use a new branch to experiment before rewriting history, and become familiar with amend, reset, and revert to maintain a clean Git history.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
