How to Use git checkout: Syntax, Examples, and Tips
Use
git checkout <branch-name> to switch branches and git checkout -- <file> to restore files to their last committed state. This command helps you move between different versions of your project or undo changes in files.Syntax
The git checkout command has two main uses:
- Switch branches:
git checkout <branch-name>moves you to the specified branch. - Restore files:
git checkout -- <file>discards changes in the file and restores it to the last commit.
The -- is used to separate branch names from file names when restoring files.
bash
git checkout <branch-name> git checkout -- <file>
Example
This example shows how to switch to a branch named feature and how to discard changes in a file named app.js.
bash
$ git checkout feature
Switched to branch 'feature'
$ git checkout -- app.js
# No output means the file was restored to last commitOutput
Switched to branch 'feature'
Common Pitfalls
Common mistakes include:
- Forgetting the
--when restoring files, which can confuse Git if a branch and file have similar names. - Trying to switch branches with uncommitted changes that conflict, causing Git to block the checkout.
- Using
git checkoutto restore files deletes local changes permanently, so be sure you want to discard them.
bash
$ git checkout app.js # Wrong if 'app.js' is a file, Git thinks it's a branch $ git checkout -- app.js # Correct way to restore the file
Quick Reference
Summary of git checkout uses:
| Use Case | Command Example | Description |
|---|---|---|
| Switch to branch | git checkout feature | Move to the 'feature' branch |
| Restore file | git checkout -- app.js | Discard changes in 'app.js' |
| Create and switch | git checkout -b new-branch | Create and switch to 'new-branch' |
Key Takeaways
Use
git checkout <branch> to switch branches safely.Add
-- before file names to restore files without confusion.Uncommitted changes can block branch switching; commit or stash them first.
Restoring files with
git checkout deletes local changes permanently.Use
git checkout -b <branch> to create and switch to a new branch.