Q: How do you discard local changes in Git across all three states: unstaged modified files, staged files in the index, and newly created untracked files? Compare git restore, git checkout, git reset, and git clean.
Practical runbook for discarding local Git modifications: unstaged edits in the working directory, staged files in the index, and untracked files/directories using modern git restore and git clean.
Want to master this scenario in a live sandbox? KodeKloud's Advanced Git Workflows, Rebase & Interactive Diagnostics covers this exact problem with hands-on terminal drills.
🛠️ Production Runbook & Step-by-Step Resolution
Zone 1: Discard Unstaged Changes in Working Directory
Files that have been edited but not yet staged with git add:
git restore .overwrites modifications in your working tree with the content from HEAD.- Warning: These edits are permanently destroyed and cannot be recovered via
git reflogbecause they were never committed!
Zone 2: Discard Staged Changes (Indexed with git add)
Files that were added to staging and need to be un-staged or discarded:
--stagedremoves the file from the commit index but preserves your text changes.--staged --worktreewipes the modification from both the staging area and disk.
Zone 3: Discard Untracked New Files and Directories
Newly created files that Git has never tracked:
git restoreandgit checkoutonly operate on tracked files; they will completely ignore new untracked files.git clean -fdxis widely used in CI/CD pipeline agents to ensure previous build artifacts (e.g., node_modules, binaries) are completely wiped.
The Safe Alternative: git stash
When you want to discard changes without permanent data destruction:
- If there is any doubt whether local code might be needed later, always
git stashinstead of hard restoring.
- To discard unstaged modified files, use git restore .; to unstage files, use git restore --staged .
- To remove newly created untracked files and directories, use git clean -fd (or -fdx in CI/CD pipelines to also purge ignored build artifacts).
- If you want to discard everything including staged and unstaged work in one step, run git reset --hard HEAD accompanied by git clean -fd.