restore
git restore
is a command used to restore working tree files. It can be used to discard changes in the working directory or to restore files from another commit. It is a more focused alternative to git checkout
for restoring files.
Basic Usage
Restore a File to the Last Committed State
To discard changes in a file and restore it to the last committed state, use:
git restore file.txtThis will discard any changes in
file.txt
and restore it to the state of the last commit.Restore Multiple Files
To restore multiple files, list them all:
git restore file1.txt file2.txtThis will discard changes in both
file1.txt
andfile2.txt
.Restore All Files in the Working Directory
To discard changes in all files in the working directory, use:
git restore .This will discard changes in all files and restore them to the state of the last commit.
Restore a File from a Specific Commit
To restore a file from a specific commit, use the
--source
option followed by the commit hash:git restore --source=<commit_hash> file.txtThis will restore
file.txt
to the state it was in at the specified commit.Unstage a File
To unstage a file that has been added to the staging area, use the
--staged
option:git restore --staged file.txtThis will unstage
file.txt
but keep the changes in the working directory.
Examples
Discard Changes in a File
git restore src/main.cThis command discards changes in
src/main.c
and restores it to the last committed state.Discard Changes in All Files
git restore .This command discards changes in all files in the working directory.
Restore a File from a Specific Commit
git restore --source=abc123 src/main.cThis command restores
src/main.c
to the state it was in at commitabc123
.Unstage a File
git restore --staged src/main.cThis command unstages
src/main.c
but keeps the changes in the working directory.
Using git restore
helps manage changes in the working directory and staging area efficiently.