The git restore
command, introduced in Git version 2.23, offers users the ability to revert changes in their working directory and staging area. This guide explores how to use the git restore
command to manage different types of restoration scenarios, such as restoring all files, staged changes, and deleted files.
Understanding git restore
The git restore
command is used to undo changes made to the working directory and staging area. It's a safer alternative to git reset
for discarding changes because it's more explicit about what it affects and doesn't alter the commit history.
Basic usage of git restore
To start using git restore
, you need to understand its basic syntax and options:
git restore [options] <paths>
<paths>
: Specifies the files or directories to restore.[options]
: Includes various flags like--source
,--staged
, and--worktree
to control the restore behavior.
How to git restore all changes
Restoring all changes in the working directory
To restore all changes in your working directory, run:
git restore .
This command reverts all modified and deleted files in the working directory to their last committed state, but does not affect the staging area (the holding zone for changes that are prepared to be committed to the repository).
Restoring all staged files
To unstage all files (i.e., restore the staging area to match the HEAD commit), use:
git restore --staged .
This command removes all changes from the staging area but leaves the working directory files as they were.
Combining restore actions
To restore all files in both the working directory and staging area, you can combine the commands:
git restore --source=HEAD --staged --worktree .
This will reset both the staging area and working directory for all files to their state in the last commit.
Specific restore scenarios
Restoring all deleted files
If you have deleted files that you want to restore:
git restore --source=HEAD <path_to_deleted_files>
You can specify individual files or use a pattern to include multiple files.
Restoring all modified files
To revert all modifications (but not deletions):
git restore --source=HEAD -- <path_to_modified_files>
This command only affects modified files, ignoring any files that have been added or deleted.
Best practices and considerations
- Check status first: Always use
git status
to review the changes you're about to restore, ensuring you do not unintentionally lose work. - Selective restoration: Instead of restoring everything, consider restoring changes file by file or section by section, especially in complex projects.
The git restore
command is a powerful tool for managing the current changes in your repository. It provides a flexible way to undo changes in your working directory and staging area, helping maintain a clean and organized code base.
For further reading see the official Git documentation.