Git Restore

The git restore command undoes changes in files. It can discard changes of your working directory, remove files from the staging area, or bring a file from an older commit. It was added in Git 2.23 to make the old git checkout command less confusing.

Syntax

git restore <file>
git restore --staged <file>
git restore --source=<commit> <file>

Prepare an example

1. Discard the changes of a file

You edited a file and you want the last committed version back.

Terminal output

$ echo "theme=broken" > config.txt
$ git status -s
M config.txt
$ git restore config.txt
$ git status -s
$ cat config.txt
theme=light

Be careful: this removes your changes for ever, and Git cannot bring them back, because they were never committed.

2. Unstage a file

You added a file to the staging area by mistake. This keeps the changes in the working directory, but removes the file from the staging area.

Terminal output

$ echo "lang=fr" > lang.txt
$ git add lang.txt
$ git status -s
M lang.txt
$ git restore –staged lang.txt
$ git status -s
M lang.txt

The status changes from M (staged) to M (modified, not staged). The edit is not lost.

3. Bring back a deleted file

Terminal output

$ rm config.txt
$ git status -s
D config.txt
M lang.txt
$ git restore config.txt
$ ls
config.txt
lang.txt

4. Restore a file from an older commit

Terminal output

$ echo "theme=dark" > config.txt
$ git commit -q -am "Switch to dark theme"
$ git restore –source=HEAD~1 config.txt
$ cat config.txt
theme=light
$ git status -s
M config.txt

The file has the old content, and the change is shown as modified. You can commit it if you want to keep this old version.

Restore everything

git restore .
git restore --staged .

Older commands for the same work

Old commandNew command
git checkout -- filegit restore file
git reset HEAD filegit restore --staged file
git checkout <commit> -- filegit restore --source=<commit> file
Note: Not sure if you want to lose the changes? Use git stash first, see Git Stash. Next: Git Commit Amend.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Discard the changes of a file
Undo the last commit but keep the changes
Revert a commit with git revert
Fix the message of the last commit
Stash your changes and bring them back
Recover a deleted branch with git reflog
Interview Questions & Answers
What is git revert?
How to undo last commit using git reset?
What is the difference between git reset and git revert?
What is the difference between soft, mixed and hard reset in Git?
What is git stash and when do you use it?
How do you change the last commit message in Git?
How do you squash commits in Git?