Using git revert

The git revert commit command is substantially similar to the command git cherry-pick commit with one important difference: it applies the inverse of the given commit. Thus, this command is used to introduce a new commit that reverses the effects of a given commit.

Like git cherry-pick, the revert doesn’t alter the existing history within a repository. Instead, it adds a new commit to the history.

A common application for git revert is to “undo” the effects of a commit that is buried, perhaps deeply, in the history of a branch. In Figure 10-8, a history of changes has been built up on the master branch. For some reason, perhaps through testing, commit D has been deemed faulty.

Before simple git revert

Figure 10-8. Before simple git revert

One way to fix the situation is to simply make edits to undo the effects of D and then commit the reversal directly. You might also note in your commit message that the purpose of this commit is to revert the changes that were caused by the earlier commit.

An easier approach is to simply run git revert:

$ git revert master~3    # commit D

The result looks like Figure 10-9, where commit D' is the inverse of commit D.

After simple git revert

Figure 10-9. After simple git revert

Get Version Control with Git now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.