Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Reverting Commits | Undoing Changes
Git Essentials

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
Note
Note

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"
Modification and direct commit

Now display the detailed information of this commit using the git show command with HEAD:

git show HEAD
The latest commit

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
Reverting the latest commit

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.
Note
Note

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
Two latest commits

Basically, as expected, a new commit was created with the inverse changes.

Note
Note

Use arrows to scroll up or down and press the q key to exit.

question mark

What does the git revert HEAD command do in Git?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 4

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 3. Chapter 4
some-alt