Git Revert and Git Reset: Explained with Examples:
Git Revert: git revert
is used to create a new commit that undoes the changes introduced by a previous commit. It's a safe way to undo changes while preserving the commit history.
Git Reset: git reset
is used to move the current branch pointer to a different commit, effectively resetting the state of the branch. It can be used to discard commits or move branches to a previous state. Be cautious as it can rewrite history.
Example Scenario: Suppose you have a repository with the following commit history:
A --- B --- C --- D (main)
Commit A: Initial state
Commit B: Added new feature
Commit C: Made some changes
Commit D: Introduced a bug
You want to undo the changes introduced by commit D and go back to the state after commit C.
Git Revert:
Reverting a Commit:
git revert D
This creates a new commit that undoes the changes from commit D, resulting in:
A --- B --- C --- D --- E (main)
- Commit E: Revert of commit D
Git Reset:
Soft Reset:
git reset --soft C
This moves the
main
branch pointer back to commit C, leaving the changes from commit D in the staging area. Your working directory will have the changes from commit D.A --- B --- C (main) \ D
Mixed Reset:
git reset --mixed C
This is the default mode. It moves the
main
branch pointer to commit C and removes the changes from commit D from the staging area. Your working directory will have the changes from commit D as uncommitted changes.A --- B --- C (main) \ D
Hard Reset:
git reset --hard C
This moves the
main
branch pointer to commit C and discards all changes introduced by commit D. Be cautious with this option as it permanently removes changes.A --- B --- C (main) \ D (unreferenced)
Diagrams:
Here's a visual representation of the commit history and the effects of using
git revert
and different modes ofgit reset
:Original commit history:
A --- B --- C --- D (main)
After using
git revert D
:A --- B --- C --- D --- E (main)
After using
git reset --soft C
:A --- B --- C (main) \ D
After using
git reset --mixed C
(default behavior):A --- B --- C (main) \ D
After using
git reset --hard C
:A --- B --- C (main) \ D (unreferenced)
Both git revert
and git reset
are powerful tools for undoing changes in a Git repository. git revert
creates a new commit to undo changes while preserving history, while git reset
moves the branch pointer to a different commit, affecting the branch's history. Be cautious when using git reset
, especially the --hard
option, as it can result in permanent data loss. Always make sure to have backups or understand the implications before using these commands.
Subscribe to my newsletter
Read articles from Shrishail Patil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Shrishail Patil
Shrishail Patil
DevOps Enthusiast | Cloud & DevOps | Kubernetes | AWS | Ansible | GIT | Terraform | Gitlab | Docker | Python | Linux | Software Testing | Data Engineering