Git & GitHub Course
Git & GitHub
/
Beginner

git restore

Definition

Introduced in Git 2.23, it is explicitly used to restore files in the working tree or staging area. It replaces the confusing file-manipulation aspects of `git checkout` and `git reset`.

Explain Like I'm New

The 'discard changes' button. If you edit a file, completely mess it up, and just want to throw your edits in the trash and go back to the last saved version, use `git restore`.

Real World Example

You delete 50 lines of CSS trying to fix a bug, realize you made it worse, and type `git restore styles.css` to instantly put those 50 lines back.

Common Use Cases

  • •Discarding uncommitted local changes
  • •Unstaging files easily

Crucial Command Flags

Flag / OptionDescription
--stagedRemove a file from the Staging Area (unstage it).
--source=[commit]Restore a file to how it looked in a specific past commit.

Terminal Output

bash / terminal
# Scenario 1: Throwing away terrible code # You edited app.js, it's broken, you want to start over. $ git restore app.js # Scenario 2: Throwing away ALL terrible code in the project $ git restore . # Scenario 3: Unstaging a file (The modern alternative to git reset) $ git add config.json # Wait, I don't want to commit config.json yet! $ git restore --staged config.json

Interview Questions

basic

  • Does `git restore` delete your recent, unsaved edits permanently?

intermediate

  • How do you unstage a file using `git restore`?

Flash Cards

Question

Delete permanently?

Click to reveal answer
Answer

YES. Be very careful. `git restore <file>` takes the file exactly as it was in the last commit and forcefully overwrites your Working Directory. Your unsaved edits are gone forever.

Question

Unstage a file?

Click to reveal answer
Answer

Use `git restore --staged <file>`. This pulls the file off the Stage, but safely leaves your edits intact in the Working Directory.