Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Reverting Changes before Staging
course content

Course Content

Git Essentials

Reverting Changes before StagingReverting Changes before Staging

Sometimes, you may find yourself in a situation where you've made modifications to your working tree but want to discard those changes before they are even staged. Let’s now explore techniques for reverting changes in Git before they are added to the staging area.

Discarding Changes with git restore

The git restore command is a versatile tool for discarding changes in your working tree. To revert changes in modified files before staging, you can use this command as follows:

Where <file> is the name of the files or its path relative to the project directory. This command reverts the specified file to the version that is staged. If the staging area is empty, it reverts the file to the version in the latest commit.

Reverting to Staged Version

Let’s first create a new file named recipe.txt which will contain a simple recipe for boiled eggs using the echo command:

We will now add this file and modify it by adding another line to it with another step of our recipe:

Oops, it seems we used the wrong operator, namely > (which overwrites the file) instead of >> (which appends a new line to the end of the file). Before we take any steps to fix it, we should check the status of our working tree and staging area:

As you can see, our initial version of the file is staged, so let’s revert our file to this version and check the status of our working tree and staging area once again:

As you can see, our working tree is now clean, so the changes were undone, and the file was reverted to the staged version.

Creating and staging the file
Reverting to staged version

Reverting to the Latest Commit

First, we should commit the creation of our recipe.txt file:

The commit is successful. Now, let's once again another line to the file with another step of our recipe and check the status of the working tree:

Oops, we made another mistake here. The step we added should be at number 7, not 10. No worries, we can revert this change to our latest commit. Let’s check the latest commit:

This commit is exactly what we need, so we can now restore the changes to this version and verify that our working tree is indeed clean:

Our working tree is clean which means that our changes were undone, and the file was restored to the version of the latest commit.

Reverting to the latest commit

Everything was clear?

Section 3. Chapter 1
some-alt