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.
$ 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.
$ 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
$ 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
$ 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 command | New command |
|---|---|
git checkout -- file | git restore file |
git reset HEAD file | git restore --staged file |
git checkout <commit> -- file | git restore --source=<commit> file |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |