Let's break down how to use git revert
to undo changes introduced by a specific commit in Git.
git revert
is a powerful command that creates a new commit which undoes the changes made in a target commit. It's a safer approach than git reset
for shared repositories because it doesn't rewrite history.git commit -m "commit message"
git revert <commit-hash>
git log --oneline
a1b2c3d (HEAD -> main) Added a new feature
e5f6g7h Fixed a critical bug
i8j9k0l Initial commit
git revert
Command:git revert a1b2c3d
Revert "Added a new feature"
This reverts commit a1b2c3d.
git log
git revert 3e1f1b2
git push origin main
git revert <oldest_commit_hash>^..<newest_commit_hash>
a1b2c3d - Added feature A (latest)
f6g7h8i - Updated tests
j1k2l3m - Initial setup for feature A
git revert j1k2l3m^..a1b2c3d
Git Revert |
Git Reset |
---|---|
Revert changes by creating new commits. |
Reset the current HEAD to a specified state. |
Creates a new commit that undoes the specified commit. |
Moves HEAD and branch pointers to the specified commit. |
Preserves commit history by adding revert commits. |
Rewrite commit history by removing commits. |
Preferred for reverting changes on shared branches. |
Should not be used for shared branches due to history rewriting. |
Syntax: git revert [options] <commit-hash> |
git reset [options] <commit> |
Action |
Command |
Description |
View commit history |
git log |
Shows commit hashes and messages |
Revert a single commit |
git revert <commit_hash> |
Creates a new commit that undoes the selected commit |
Revert multiple commits (range) |
git revert <oldest_hash>^..<newest_hash> |
Reverts all commits in the specified range |
Revert a merge commit |
git revert -m 1 <merge_commit_hash> |
Reverts a merge (use -m 1 to specify mainline) |
Push changes after revert |
git push origin <branch_name> |
Pushes the new revert commit to remote repo |
Resolve conflicts (if any) |
git add . → git revert --continue |
Handles conflicts during revert |