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

Conteúdo do Curso

Git Essentials

Git Essentials

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

book
Reverting 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.

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.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 1
We're sorry to hear that something went wrong. What happened?
some-alt