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
No Content Found.
Interview Questions & Answers
No Content Found.