Reverting Commits
Swipe to show menu
In the vast landscape of version control with Git, one common scenario is the need to undo changes introduced by a specific commit. This could be due to various reasons such as discovering a bug, realizing that a feature is not ready for production, or simply wanting to take a different approach.
Luckily, Git provides the git revert command to create a new commit that undoes the changes introduced by the specific commit by making the inverse of the changes in that commit.
Reverting the Last Commit
To revert the last commit, use the following command:
git revert HEAD
HEAD is a pointer to the latest commit on the current branch.
Since there is only one branch, HEAD points to the latest commit. This command creates a new commit that reverses the changes from the previous one. Git opens the default text editor to allow editing of the commit message if needed. Save and close the editor to complete the revert.
Example Workflow
First, add a new line to the recipe.txt file with the next step and directly commit the change, skipping the staging area:
echo "8. Peel the eggs" > recipe.txt
git commit -a -m "Add another step to the recipe"
Now display the detailed information of this commit using the git show command with HEAD:
git show HEAD
Oops, all previous lines were deleted because the wrong output operator was used — > instead of >>, which overwrote the file.
No worries; use the git revert command to undo these changes in the latest commit:
git revert HEAD
As you can see, the default text editor opens (Vim in this case) with a default commit message. For now, leave it as is, but in real projects, it is recommended to include the reason for the rollback, for example:
Revert "Add another step to the recipe"
Reason for rollback: the recipe.txt was overwritten.
This reverts commit b1148490543882f038069a0233a5d7e0b33f6221.
To save changes and exit Vim, press the Escape key and two capital Z letters.
Finally, view the changes in the two most recent commits:
git log -p -2
Basically, as expected, a new commit was created with the inverse changes.
Use arrows to scroll up or down and press the q key to exit.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat