How to Unstage a File in Git: Simple Commands Explained
To unstage a file in Git, use the command
git restore --staged <file>. This removes the file from the staging area but keeps your changes in the working directory.Syntax
The command to unstage a file in Git is:
git restore --staged <file>: Removes the specified file from the staging area.<file>: The path to the file you want to unstage.
This command keeps your changes in the file but tells Git not to include it in the next commit.
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
git add example.txt # File is now staged git restore --staged example.txt # File is unstaged but changes remain
Output
On branch main
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: example.txt
Unstaged changes after restore:
On branch main
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
modified: example.txt
Common Pitfalls
Some common mistakes when unstaging files in Git include:
- Using
git reset HEAD <file>which also unstages but is older syntax; prefergit restore --stagedfor clarity. - Confusing unstaging with discarding changes; unstaging keeps your edits, while discarding removes them.
- Not specifying the correct file path, which causes the command to fail silently or unstage wrong files.
bash
git reset HEAD example.txt # Older way to unstage # Preferred modern way: git restore --staged example.txt
Quick Reference
Remember these tips when unstaging files:
- Unstage without losing changes: Use
git restore --staged <file>. - Check status: Run
git statusto see staged and unstaged files. - Discard changes (if needed): Use
git restore <file>to remove changes from working directory.
Key Takeaways
Use
git restore --staged <file> to unstage files without losing changes.Unstaging removes files from the next commit but keeps your edits intact.
Check your staging area anytime with
git status.Avoid confusing unstaging with discarding changes; they are different actions.
Prefer
git restore --staged over older commands like git reset HEAD.