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:
Example:This removes all uncommitted changes in that file.
Older syntax (still works):
1git restore <file>Example:
1git restore index.htmlOlder syntax (still works):
1git checkout -- <file>22.2 Discarding All Local Changes
To discard all uncommitted changes in the working directory:
⚠️ This cannot be undone.
1git restore .⚠️ This cannot be undone.
22.3 Unstaging Changes (Keep File Changes)
If you accidentally staged a file:
Example:
This removes the file from the staging area but keeps the file changes.
1git restore --staged <file>Example:
1git restore --staged app.jsThis 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:
This:
• Clears staging
• Discards all local changes
• Resets to the last commit
⚠️ Very destructive — use only when you are sure.
1git reset --hardThis:
• 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:
• Git prevents switching if changes would be lost
• You must either commit, stash, or discard changes
Example:
1git restore .
2git switch main22.6 When Not to Discard
Do not discard changes when:
• You might need the work later
• You are unsure what changed
Instead, use:
Stashing is safer and reversible (covered later).
• You might need the work later
• You are unsure what changed
Instead, use:
1git stashStashing 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.
• 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.