The git revert command is a method to undo changes that have already been committed to the version history in Git. Unlike directly modifying history (such as with git reset), git revert creates a new commit that effectively undoes the changes made by the previous commit. This is a safe way to revert changes because it does not rewrite the project history.
To use git revert, follow these steps:
- Identify the commit to revert: First, determine which commit you want to revert. Use
git logto view the commit history and find the hash of the commit to revert. For example:
bashgit log --oneline
- Execute the revert operation: Next, run the
git revertcommand with the hash of the commit to revert. For example, if the commit hash isabc1234, execute:
bashgit revert abc1234
This will open a text editor for you to edit the commit message. After saving and closing the editor, Git will create a new commit to undo the specified changes.
-
Resolve potential conflicts: If conflicts arise during the revert process, Git will not create a new commit and will require you to manually resolve the conflicts first. After resolving the conflicts, mark the resolved files using
git addand complete the revert operation withgit revert --continue. -
Push changes to the remote repository: Once the
git revertoperation is complete and all conflicts are resolved, push the changes to the remote repository usinggit push. For example:
bashgit push origin main
where main is the branch you are currently on; replace it with the appropriate branch name if working on a different branch.
Example Scenario: Imagine a scenario where I recently introduced a feature to the project, but it caused issues that need to be undone. The commit hash is def4567. I will proceed as follows:
- View the commit history to confirm the hash:
bashgit log --oneline
- Execute the revert operation:
bashgit revert def4567
- If conflicts occur, resolve them and add the changes:
bashgit add . git revert --continue
- Finally, push the changes to the remote repository:
bashgit push origin main
This way, I successfully used git revert to undo a problematic commit without affecting the project's history.