← Back to Git Course | Chapter 2: Basic Commands | Lesson 16 of 18

Git restore Command

Discarding Working Directory Changes

git restore <file> reverts an unwanted edit back to the file's last committed state, discarding your local, unstaged changes -- it's the modern, more explicit replacement for using git checkout to throw away edits.

Example: Discarding Working Directory Changes

bash
git restore file.txt

Unstaging a File

If a file is already staged with git add but you've changed your mind about including it in the next commit, git restore --staged <file> unstages it while leaving your actual edits in the working directory untouched.

Example: Unstaging a File

bash
git restore --staged file.txt

Restoring from a Specific Commit

git restore --source=<commit> <file> pulls a file's contents from any specific point in history, not just the last commit, letting you recover an older version without checking out that whole commit.

Example: Restoring from a Specific Commit

bash
git restore --source=a1b2c3d file.txt

Unstaging and Restoring Together

Combining --staged and --source in one command both unstages a file and resets its working copy to a past commit's version in a single step, rather than doing it as two separate commands.

Example: Unstaging and Restoring Together

bash
git restore --staged --source=a1b2c3d file.txt

Patch Mode Restoration

git restore -p <file> opens an interactive, hunk-by-hunk prompt so you can discard only some of a file's changes and keep the rest -- useful when a file mixes an unwanted experiment with a fix you actually want to keep.

Example: Patch Mode Restoration

bash
git restore -p file.txt

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.