descartar-cambios-en-git-con-restore

Discarding Changes with Git Restore

  • 4 min

The git restore command is the command for discarding or undoing local changes in the working directory and removing files from the Staging Area.

During development, sometimes you make modifications that you ultimately don’t want to keep. You’re editing a file, you start changing things, you test a crazy idea, and in the end, you don’t like what you changed.

Whether you’re experimenting or you’ve made a mistake, we need a way to revert a file to its previous state. We need a “Ctrl+Z”, but for Git.

In this article, we’ll see how to use this git restore to discard changes in our working directory or remove files from the Staging Area.

In the past, this task was done with git checkout, a command overloaded with functions that often caused confusion.

To solve this, modern versions of Git introduced git restore.

Discarding local changes

This is the most common case. I’ve broken the file, I want to go back. You don’t want your current version of the file, you want it to be identical to the last commit again.

The command is:

git restore nombre_archivo.ext
Copied!

You can also use . to restore all modified files in the current folder:

git restore .
Copied!

Git goes to its database (the last commit), finds that version of the file, and copies it to your Working Directory, overwriting whatever you had written.

Be careful! This operation is destructive. Unlike other things in Git, with restore there is no undo. If you restore a file that you hadn’t saved with a commit, the changes you had written in it are lost forever.

Removing files from the Staging Area

This is the other main use of restore. Let’s assume the following case:

  1. You modify app.js (a good change).
  2. You modify claves.txt (a file with passwords that you do NOT want to upload).
  3. Out of habit, you type git add ..

Now you have claves.txt in the Staging Area. If you commit, you’re in trouble, because it would be recorded in Git’s history.

You need to remove it from the Stage, but without deleting the file from your disk (because you want your password file).

git restore --staged claves.txt
Copied!

By using the --staged flag, we are telling Git: “Restore the version of the file that is in the Stage to match the one from the last commit”.

The result is that the file is removed from the staging area and goes back to being simply Modified (or Untracked if it was new).

In the past, this was done with the cryptic git reset HEAD claves.txt. Now, with restore, it’s much more logical.