Git restore & checkout
In this page:
Discarding Unstaged Local Changes
git restore <file> throws away uncommitted local edits to a file and resets it to match the last commit (or a specified commit with --source). It's the modern, safer-named replacement for the old git checkout -- <file> syntax that used to double as both a file-restore and branch-switch command.
Example: Discarding Unstaged Local Changes
git restore file.txt
Unstaging Staged Files
If you staged a file with git add but decide you don't want to commit it yet, git restore --staged <file> unstages it — moving it back to "modified but not staged" — without touching your actual edits in the working directory. This is the fix for the common "oops, I staged the wrong file" moment.
Example: Unstaging Staged Files
git restore --staged file.txt
Switching Between Branches
git checkout <branch> (or the newer git switch <branch>) updates your working directory to match that branch's latest commit. Git will refuse the switch if it would silently overwrite uncommitted changes, so committing or stashing first avoids a confusing error mid-switch.
Example: Switching Between Branches
git checkout main
git switch main
Creating and Switching to New Branches
git checkout -b <name> (or git switch -c <name>) creates a new branch from your current position and switches to it in one step, instead of running git branch <name> followed by a separate switch command — the shortcut most people reach for in daily use.
Example: Creating and Switching to New Branches
git checkout -b feature-x
git switch -c feature-x
Restoring Files from Specific Commits
git restore --source=<commit> <file> (or the older git checkout <commit> -- <file>) pulls just one file's contents from an arbitrary past commit into your working directory, without touching any other files or moving your branch pointer — useful for recovering a single deleted or overwritten file.
Example: Restoring Files from Specific Commits
git restore --source=a1b2c3d file.txt
git checkout a1b2c3d -- file.txt
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: