Git Revert and Git Reset: Explained with Examples:

DevOps Enthusiast | Cloud & DevOps | Kubernetes | AWS | Ansible | GIT | Terraform | Gitlab | Docker | Python | Linux | Software Testing | Data Engineering
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 DThis 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 CThis moves the
mainbranch 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) \ DMixed Reset:
git reset --mixed CThis is the default mode. It moves the
mainbranch 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) \ DHard Reset:
git reset --hard CThis moves the
mainbranch 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 revertand 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) \ DAfter using
git reset --mixed C(default behavior):A --- B --- C (main) \ DAfter 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.




