How to Use git checkout to Undo Changes Quickly
Use
git checkout -- <file> to undo changes in a file by restoring it to the last committed state. To switch branches or undo changes in the working directory, use git checkout <branch> or git checkout -- <file> respectively.Syntax
The git checkout command has two main uses for undoing changes:
git checkout -- <file>: Reverts the specified file in your working directory to the last committed version, discarding local changes.git checkout <branch>: Switches your working directory to the specified branch.
The double dash -- tells Git that what follows is a file path, not a branch name.
bash
git checkout -- <file> git checkout <branch>
Example
This example shows how to undo changes in a file named app.js using git checkout. It restores the file to the last committed state, discarding any edits made since then.
bash
echo 'console.log("Hello World")' > app.js
# Edit app.js manually or with an editor
# Now undo changes:
git checkout -- app.js
# Check status
git statusOutput
On branch main
Your branch is up to date with 'origin/main'.
nothing to commit, working tree clean
Common Pitfalls
Common mistakes when using git checkout to undo changes:
- Forgetting the
--before the file name, which can cause Git to think you want to switch branches. - Using
git checkouton untracked files does nothing; it only works on files tracked by Git. - Undoing changes with
git checkoutis permanent for that file’s working copy and cannot be undone.
Always double-check which files you are discarding changes from to avoid losing work.
bash
git checkout app.js # Wrong: tries to switch to branch named 'app.js' git checkout -- app.js # Correct: reverts changes in the file
Quick Reference
| Command | Purpose |
|---|---|
| git checkout -- | Undo changes in a file, restore last commit version |
| git checkout | Switch to another branch |
| git checkout -- . | Undo changes in all files in current directory |
| git checkout HEAD -- | Explicitly restore file from last commit |
Key Takeaways
Use 'git checkout -- ' to undo changes in a tracked file safely.
Always include '--' before file names to avoid branch switching mistakes.
Changes undone by 'git checkout' cannot be recovered unless committed or stashed.
Use 'git checkout ' to switch branches without affecting uncommitted changes.
For undoing all changes in the directory, use 'git checkout -- .'