0
0
GitHow-ToBeginner · 3 min read

How to Use git restore: Syntax, Examples, and Tips

Use git restore to undo changes in your working directory or staging area. It can discard unstaged changes or unstage files by specifying options like --staged. This command helps you safely revert files to their last committed state.
📐

Syntax

The basic syntax of git restore is:

  • git restore [options] <file>...

Key parts:

  • <file>: The file(s) you want to restore.
  • --staged: Restore files in the staging area (unstage changes).
  • --worktree: Restore files in the working directory (discard unstaged changes). This is the default.
bash
git restore [--staged] <file>...
git restore [--worktree] <file>...
💻

Example

This example shows how to discard changes in a file and how to unstage a file from the staging area.

bash
# Suppose you modified file.txt but want to discard changes
$ git restore file.txt

# Suppose you staged file.txt but want to unstage it
$ git restore --staged file.txt
⚠️

Common Pitfalls

Common mistakes when using git restore include:

  • Forgetting that git restore file.txt only affects the working directory, not the staging area.
  • Using git restore without specifying files, which does nothing.
  • Confusing git restore with git reset, which affects commits and staging differently.

Always double-check which area (working directory or staging) you want to restore.

bash
Wrong: git restore
# Does nothing because no file specified

Right: git restore file.txt
# Discards changes in working directory

Wrong: git restore --staged file.txt
# Correct usage but remember it unstages changes, does not discard working directory changes

Right: git restore --staged file.txt
# Unstages the file
📊

Quick Reference

CommandEffect
git restore Discard unstaged changes in working directory
git restore --staged Unstage file from staging area
git restore --worktree Explicitly discard changes in working directory
git restore --source= Restore file from specific commit

Key Takeaways

Use git restore to discard changes in working directory or unstage files safely.
Specify --staged to unstage files, omit it to discard unstaged changes.
Always specify the file(s) you want to restore; no files means no action.
git restore does not affect commits; use git reset for commit history changes.
Check git status before and after to confirm changes.