Q12 of 40 · Git

How do you discard local uncommitted changes?

GitJuniorgitdiscard-changesrestorecleanfundamentals

Short answer

Short answer: For unstaged files: git restore <file> (modern) discards working-directory changes. For staged files: git restore --staged <file> to unstage, then git restore <file> to discard. git restore . resets the entire working tree. For untracked files git clean -fd removes them — always dry-run with -n first.

Detail

Discarding unstaged changes (working directory):

git restore tests/LoginTest.java   # restore one file
git restore .                       # restore everything in the working tree

The old equivalent is git checkout -- <file> — still valid but less clear in meaning.

Unstaging staged changes (moving from staging area back to working directory):

git restore --staged tests/LoginTest.java

Removing untracked files (not tracked by Git, so not covered by restore):

git clean -n         # dry run — shows what WOULD be deleted
git clean -f         # delete untracked files
git clean -fd        # delete untracked files and directories
git clean -fdx       # also delete files ignored by .gitignore (use carefully!)

Nuclear option — reset to last commit:

git reset --hard HEAD   # discard all staged and unstaged changes
git clean -fd           # also remove untracked files

⚠️ These are irreversiblegit restore and git reset --hard can't be undone with git reflog because the changes were never committed.

// EXAMPLE

# Discard changes in one file (unstaged)
git restore tests/LoginTest.java

# Discard ALL unstaged changes in the whole repo
git restore .

# Unstage a file you accidentally staged
git restore --staged tests/LoginTest.java

# Remove untracked files — ALWAYS dry-run first
git clean -n          # shows what would be deleted
git clean -fd         # actually delete files and dirs

# Complete reset — discard everything and remove untracked files
git reset --hard HEAD
git clean -fd

# Tip: if unsure, stash instead of discard (stash is reversible)
git stash             # saves changes temporarily
# ... decide you don't want them ...
git stash drop        # discard the stash

// WHAT INTERVIEWERS LOOK FOR

Using git restore (modern) over git checkout --, knowing that untracked files need git clean (not git restore), and always dry-running git clean with -n before -f. The stash-as-safer-alternative tip shows experience.

// COMMON PITFALL

Using git reset --hard HEAD to discard unstaged changes when git restore . is cleaner and more explicit. Also: running git clean -fd without -n first and accidentally deleting generated files that take hours to recreate.