git revert
git revert
: revert changes from a specific commit.
git revert
creates a new commit that inverses the changes made by the specified commit, effectively canceling out its effects without altering the commit history.
The purpose of git revert
is to provide a safe and clean way to undo changes in a repository without rewriting its history. This is particularly useful in collaborative environments, where rewriting history (e.g., using git reset
) can cause confusion and conflicts for other developers working on the same project.
When you use git revert
, Git creates a new commit that contains the inverse of the changes made in the original commit. This new commit is then added to the repository's history, leaving a clear record of both the original changes and their reversal.
git revert
is especially helpful when you need to undo a specific change that was introduced in a previous commit without affecting any of the commits that came after it. This allows you to surgically remove a problematic change while preserving the integrity of your commit history.
Examples
Let's say you have a commit history like this:
a1b2c3d (HEAD -> main) Update README
b2c3d4e Fix typo in main code
c3d4e5f Add new feature
d4e5f6g Initial commit
If you want to revert the Fix typo in main code
commit (b2c3d4e
), you can use git revert
:
git revert b2c3d4e
This will open your default text editor, asking you to enter a commit message for the revert commit. After you save and close the editor, Git will create a new commit that inverses the changes made in b2c3d4e
:
a1b2c3d (HEAD -> main) Revert "Fix typo in main code"
b2c3d4e Update README
c3d4e5f Fix typo in main code
d4e5f6g Add new feature
e5f6g7h Initial commit
Now, the effects of the Fix typo in main code
commit have been undone, but the commit itself is still part of the history, and a new commit has been created to record the reversal of its changes.