
Revert in Git
π Git Revert: Undo Commits Without Losing History
git revert
is used to undo a commit without deleting history. Unlike git reset --hard
, it creates a new commit to reverse the changes.
π When to Use git revert
?
β
Safe for shared repositories (e.g., GitHub, GitLab, Bitbucket)
β
Does NOT delete commits but creates a new one to undo changes
β
Good for undoing specific commits without affecting others
1οΈβ£ Revert the Last Commit
git revert HEAD
β‘ This reverses the last commit and creates a new commit.
2οΈβ£ Revert a Specific Commit
1οΈβ£ Find the commit hash:
git log --oneline
Example output:
a1b2c3d Fixed a bugf6g7h8i Added new feature
2οΈβ£ Revert that commit:
git revert a1b2c3d
β‘ This creates a new commit that undoes only that commit, keeping others intact.
3οΈβ£ Revert Multiple Commits
git revert HEAD~2..HEAD
β‘ This reverts the last two commits (HEAD
to HEAD~2
).
4οΈβ£ Revert Without Creating a Commit
If you donβt want an automatic commit, use:
git revert -n <commit-hash>
β‘ Changes will be staged, and you can commit manually:
git commit -m "Reverted commit <hash>"
π₯ Example Workflow
git log --onelinegit revert f6g7h8i # Reverts "Added new feature"git push origin main
π― Summary
Command | Effect |
---|---|
git revert HEAD | Undo last commit (creates new commit) |
git revert <commit-hash> | Undo specific commit |
git revert HEAD~2..HEAD | Undo last two commits |
git revert -n <commit-hash> | Revert without committing |
π‘ Use git revert
instead of git reset --hard
for safe changes in shared repositories.