How to Use git revert: Undo Commits Safely
Use
git revert <commit-hash> to undo a commit by creating a new commit that reverses the changes. This keeps your project history intact and safe for shared repositories.Syntax
The basic syntax of git revert is:
git revert <commit-hash>: Reverts the specified commit by creating a new commit that undoes its changes.--no-commit: Applies the revert changes but does not create a commit immediately, allowing you to edit or combine changes.--edit: Opens the commit message editor to modify the default revert message.
bash
git revert [--no-commit] [--edit] <commit-hash>
Example
This example shows how to revert a commit with hash abc1234. It creates a new commit that undoes the changes from that commit.
bash
git revert abc1234
Output
Created new commit to undo changes from abc1234
[main 9f8e7d6] Revert "Add feature X"
1 file changed, 2 deletions(-)
Common Pitfalls
Common mistakes when using git revert include:
- Trying to use
git reverton uncommitted changes (it only works on commits). - Confusing
git revertwithgit reset; revert keeps history safe by adding a new commit, reset changes history. - Not resolving conflicts that can happen if the reverted commit overlaps with later changes.
Always check the commit hash carefully and test after revert.
bash
git revert wronghash # Error: could not revert commit # Correct usage: git revert abc1234
Output
error: could not revert commit wronghash
fatal: bad revision 'wronghash'
Quick Reference
| Command | Description |
|---|---|
| git revert | Undo a commit by creating a new commit that reverses it |
| git revert --no-commit | Apply revert changes without committing immediately |
| git revert --edit | Edit the revert commit message before committing |
| git revert HEAD | Revert the latest commit |
Key Takeaways
Use git revert to safely undo commits by creating new commits that reverse changes.
Always specify the correct commit hash to revert the intended commit.
git revert keeps project history intact, unlike git reset which rewrites history.
Conflicts can occur during revert and must be resolved before committing.
Use --no-commit to review changes before finalizing the revert commit.