Git Restore: Discard Unstaged Changes Safely
Restore the working file from the index
Use git restore -- notes.txt when you deliberately want to discard unstaged edits to a tracked file. It copies the indexed version into the working tree by default, not necessarily the last commit. This can permanently lose edits. In the restore lab, start with committed Tea, then stage Rice and edit the file to Milk. Inspect and save a separate copy of the working file before proceeding.
git status --shortgit diff -- notes.txtgit diff --cached -- notes.txtcp notes.txt ../restore-notes-backup.txtgit restore -- notes.txtgit status --shortThe working file now contains Rice, the index still contains Rice, and HEAD still contains Tea. Status changes from MM to M in the first column. The backup contains Milk.
Restore a missing tracked file
In the same disposable lab the staged Rice content is still available. Simulate an accidental deletion only in this lab; restore recovers the indexed content. An ordinary untracked file has no indexed version to restore.
Rice is restored; the staged change remains. HEAD is unchanged.
Choose the source explicitly
In the same fixture, --source=HEAD selects the committed snapshot instead of the index. This updates the working file only unless you also request --staged. Inspect both differences afterwards. Do not use a broad path such as . merely to remove one unwanted edit.
git restore --source=HEAD -- notes.txtgit status --shortgit diff -- notes.txtThe working file is Tea again but the index is Rice. Status is MM; HEAD has not moved.
Practice
Predict the file contents when the index contains Rice but HEAD contains Tea. Check your prediction with the first fixture. Keep the backup until you no longer need it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Git Restore: Discard Unstaged Changes Safely — knowledge check
Reason about undo operations, affected states and preservation of work.
What does plain restore use as its default source?
HEAD has Tea, index Rice, working file Milk. After plain restore?
What must you do before discarding a valuable unstaged edit?
A tracked file was deleted from the working tree but exists in index. What restores it?
What changes with --source=HEAD and no --staged?