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

Course Content

Git Essentials

Git Essentials

1. Introduction to Git
2. More Advanced Interaction
3. Undoing Changes
4. Working with Branches in Git

book
Reverting Commits

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:

Note

HEAD is a pointer to the latest commit on the current branch.

Since we work with only a single branch now, HEAD simply points to the latest commit. This command creates a new commit that undoes the changes made in the last commit. Git will open the default text editor to let you modify the commit message if necessary. Save and close the editor to complete the revert.

Example Workflow

Let’s first add a new line to our recipe.txt file with another step and directly commit this change skipping the staging area:

We can now show the detailed info of this commit using the git show command with HEAD:

Oops, all the previous lines were deleted. It seems we used the wrong output operator, namely > instead of >>, which resulted in our file being overwritten. No worries, we’ll use the git revert command to undo these changes in our latest commit:

As you can see, the default text editor is opened (Vim in my case) with the default commit message. For now, we’ll leave it as it is, but in real-world projects it is often better to add the reason for rollback, for example:

Note

To save changes and exit Vim, press the Escape key and two capital Z letters.

Finally, we can take a look at the changes in the two latest commits:

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

Note

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

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 4
We're sorry to hear that something went wrong. What happened?
some-alt