How to Use git restore staged to Unstage Files
Use
git restore --staged <file> to unstage a file that was added to the staging area. This command removes the file from the staged snapshot but keeps your changes in the working directory.Syntax
The basic syntax of git restore --staged is:
git restore: The command to restore files in Git.--staged: Option to target the staging area (index) instead of the working directory.<file>: The file or files you want to unstage.
bash
git restore --staged <file>
Example
This example shows how to unstage a file named example.txt after adding it to the staging area.
bash
echo "Hello" > example.txt
# Add the file to staging
git add example.txt
# Check status shows it staged
git status
# Unstage the file
git restore --staged example.txt
# Check status again
git statusOutput
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: example.txt
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
new file: example.txt
Common Pitfalls
Common mistakes when using git restore --staged include:
- Forgetting the
--stagedflag, which restores the file in the working directory instead of unstaging. - Expecting this command to discard changes; it only removes the file from staging but keeps your edits.
- Trying to unstage files that are not staged, which has no effect.
bash
git restore example.txt # This restores working directory, not unstaging git restore --staged example.txt # Correct way to unstage
Quick Reference
Use this quick guide to remember how to unstage files:
| Command | Purpose |
|---|---|
| git add | Stage changes for commit |
| git restore --staged | Unstage changes but keep edits |
| git restore | Discard changes in working directory |
| git status | Check current staging and working directory state |
Key Takeaways
Use git restore --staged to remove files from the staging area without losing changes.
The --staged flag targets the index (staging area), not the working directory.
git restore without --staged affects the working directory, discarding changes.
Always check git status to confirm the state of your files before committing.
Unstaging does not delete your edits; it just removes them from the next commit.