How to revert previous commit in git?
To revert a previous commit in Git, you can use the
git revert command. The
git revert command creates a new commit that undoes the changes introduced by a specific commit, effectively reverting those changes in the commit history. This is a safer way to undo changes compared to using
git reset, as it preserves the commit history and does not alter the repository’s recorded history.
Here’s the basic syntax for reverting a commit:
git revert <commit-hash>
<commit-hash>: The SHA-1 hash of the commit you want to revert. You can find the commit hash in the commit history using
Here are the steps to revert a previous commit:
- First, make sure your working directory is clean (no uncommitted changes). You can use
git statusto check the status of your repository.
- Find the commit hash of the commit you want to revert. Use
git logto view the commit history, and copy the hash of the commit you wish to revert.
- Run the
git revertcommand with the commit hash you want to revert. For example:
git revert abc1234
abc1234 with the actual commit hash.
- Git will open your default text editor to enter a commit message for the revert. The default message will indicate that the revert is undoing the changes of a specific commit. You can modify the message as needed, save the file, and close the editor.
- A new commit will be created that undoes the changes introduced by the specified commit.
- Finally, push the new commit to the remote repository if needed:
git push origin <branch-name>
<branch-name> with the name of the branch you are working on.
After the revert, the changes introduced by the reverted commit will be effectively undone, and a new commit will be added to the history to record the reversion. It’s important to note that
git revert creates a new commit, so it’s safe to use even if the original commit has already been pushed and shared with others. The history remains intact, and the revert can be easily reverted itself if necessary.