git checkout — Switching Branches
The git checkout command switches between branches (or commits). When you switch branches, Git updates your working directory to match the branch's latest commit.
Switching Branches
git checkout feature
This moves HEAD to the feature branch and updates your files.
Create + Switch in One Step
git checkout -b new-feature
This is a shortcut that creates a new branch and switches to it immediately. It's the most common way to start working on something new.
The Modern Alternative: git switch
Git 2.23 introduced git switch as a clearer alternative:
git switch feature # switch to existing branch
git switch -c new-feature # create and switch
Both checkout and switch work — use whichever you prefer.
Try it!
Your repo has one commit on main. Practice the full branch workflow:
- Create and switch to a new branch:
git checkout -b feature - Create a file and commit:
echo "feature work" > feature.txtthengit add feature.txtthengit commit -m "Add feature" - Switch back to main:
git checkout main - Notice that
feature.txtis gone — it only exists on thefeaturebranch!
Watch the graph update as you create commits on different branches.
Detached HEAD
If you checkout a specific commit (not a branch), you enter detached HEAD state:
git checkout abc1234
In this state, new commits won't belong to any branch. This is useful for inspecting old code, but don't make commits here unless you know what you're doing.