Discarding Changes

22.1 Discarding Changes in a File (Working Directory)

To discard changes in a specific file and restore it to the last commit:
1git restore <file>

Example:
1git restore index.html
This removes all uncommitted changes in that file.

Older syntax (still works):
1git checkout -- <file>

22.2 Discarding All Local Changes

To discard all uncommitted changes in the working directory:
1git restore .

⚠️ This cannot be undone.

22.3 Unstaging Changes (Keep File Changes)

If you accidentally staged a file:
1git restore --staged <file>

Example:
1git restore --staged app.js

This removes the file from the staging area but keeps the file changes.

22.4 Discarding Both Staged and Unstaged Changes

To completely reset the working directory and staging area:
1git reset --hard

This:
Clears staging
Discards all local changes
Resets to the last commit
⚠️ Very destructive — use only when you are sure.

22.5 Discarding Changes by Switching Branches

When switching branches:
Git prevents switching if changes would be lost
You must either commit, stash, or discard changes

Example:
1git restore . 2git switch main

22.6 When Not to Discard

Do not discard changes when:
You might need the work later
You are unsure what changed

Instead, use:
1git stash

Stashing is safer and reversible (covered later).

22.7 Key Takeaways

Discarding applies only to uncommitted changes.
git restore <file> discards changes in a file.
git restore . discards all working directory changes.
git restore --staged unstages files without losing edits.
git reset --hard is destructive and irreversible.
When unsure, stash instead of discarding.