“git revert” Command Examples

The git revert command in Git is a powerful tool that allows you to create new commits that effectively undo the changes introduced by earlier commits. It’s a way to “reverse” the effects of specific commits while preserving the history and maintaining a clear record of the changes. Here’s a more detailed explanation of how git revert works:

  • Creating Reverting Commits: The primary purpose of git revert is to create new commits that undo the changes introduced by one or more specific commits. These new commits are essentially the opposite of the original commits.
  • Maintaining History: Unlike some other Git commands, git revert doesn’t modify existing commits. Instead, it creates new commits that contain changes that reverse the original commits. This ensures that the history remains intact and doesn’t become confusing.
  • Safe Reversion: Reverting commits using git revert is a safe operation, suitable for public repositories and collaboration. It allows you to fix issues introduced by previous commits without altering the shared history that others might have based their work on.
  • Reverting Single Commits: To revert a single commit, you provide its commit hash to git revert.
  • Reverting Multiple Commits: You can also revert a range of commits, providing a range of commit hashes.
  • Conflict Resolution: Just like with regular merges and rebases, conflicts can arise during the git revert process. If Git encounters changes that conflict with the reversion, you’ll need to resolve these conflicts manually.
  • Commit Message: When you perform a git revert, Git prompts you to edit the commit message for the new revert commit. This allows you to provide context about why you’re reverting the changes.
  • Rolling Back Mistakes: git revert is especially useful for rolling back changes that were committed in error, without disrupting the overall history of the repository.
  • Collaboration and Public Repositories: Since git revert creates new commits that don’t alter the existing history, it’s well-suited for public repositories and collaboration where history preservation is crucial.
  • Clear Record of Reverts: Using git revert results in a clear and transparent record of reversions in the commit history. It’s easy to see which commits were reverted and why.

“git revert” Command Examples

1. Revert the most recent commit:

# git revert HEAD

2. Revert the 5th last commit:

# git revert HEAD~4

3. Revert multiple commits:

# git revert branch_name~5..branch_name~2

4. Don’t create new commits, just change the working tree:

# git revert -n 0c01a9..9a1743

Summary

In summary, git revert is a valuable tool for undoing specific changes while maintaining a clear history in your Git repository. It’s particularly useful for addressing issues, fixing mistakes, and maintaining a reliable and coherent history in collaborative projects.

Related Post