Git checkout Command
In this page:
Switching to an Existing Branch
git checkout <branch> switches your working directory to match another branch's files -- it's one of Git's oldest and most overloaded commands, which is part of why git switch was introduced later to split out just this behavior.
Example: Switching to an Existing Branch
git checkout main
Creating and Switching Branches
git checkout -b <new-branch> creates a brand-new branch from your current position and switches onto it immediately, combining what would otherwise be two separate commands (git branch then git checkout) into one.
Example: Creating and Switching Branches
git checkout -b feature-signup
Restoring Files
git checkout -- <file> discards uncommitted local changes to a specific file, reverting it back to whatever was last committed -- useful for throwing away an experiment on one file without touching anything else you've changed.
Example: Restoring Files
git checkout -- file.txt
Detached HEAD State
Checking out a specific commit hash or tag instead of a branch name puts you in a 'detached HEAD' state -- you can still look around and even make commits, but those commits won't belong to any branch and can be lost once you switch away.
Example: Detached HEAD State
git checkout a1b2c3d
Returning to Safety
From a detached HEAD, switching back to any actual branch name (git checkout main) returns you to normal tracked development -- if you made commits you want to keep while detached, create a branch from them first before switching away.
Example: Returning to Safety
git checkout main
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: