0
0
Gitdevops~5 mins

git revert to undo a commit safely - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you make a change in your project that you want to undo without removing the history. git revert helps you undo a commit by creating a new commit that reverses the changes safely.
When you want to undo a change but keep the project history intact.
When you have already shared your commits with others and cannot rewrite history.
When you want to fix a mistake in a previous commit without deleting it.
When you want to undo a commit on the main branch without causing conflicts.
When you want to keep a clear record of what was undone and why.
Commands
This shows the last three commits with their short IDs and messages so you can choose which commit to revert.
Terminal
git log --oneline -3
Expected OutputExpected
a1b2c3d Fix typo in README 4e5f6g7 Add user login feature 8h9i0j1 Initial commit
--oneline - Shows each commit in a single line for easy reading
This creates a new commit that undoes the changes made in the commit with ID 4e5f6g7. It does not delete the original commit.
Terminal
git revert 4e5f6g7
Expected OutputExpected
[main 9k8l7m6] Revert "Add user login feature" 1 file changed, 10 deletions(-)
Check the last three commits again to see the new revert commit added on top.
Terminal
git log --oneline -3
Expected OutputExpected
9k8l7m6 Revert "Add user login feature" a1b2c3d Fix typo in README 4e5f6g7 Add user login feature
--oneline - Shows each commit in a single line for easy reading
Key Concept

If you remember nothing else from this pattern, remember: git revert safely undoes a commit by making a new commit that reverses changes without deleting history.

Common Mistakes
Using git reset to undo commits that have been shared with others.
git reset changes history and can cause conflicts for others who already have the commits.
Use git revert to undo changes safely without rewriting history.
Not specifying the correct commit ID when running git revert.
Reverting the wrong commit can undo unintended changes.
Use git log --oneline to find the exact commit ID before reverting.
Summary
Use git log --oneline to find the commit ID you want to undo.
Run git revert with the commit ID to create a new commit that reverses the changes.
Check the commit history again to confirm the revert commit was added.