Tour of Git
Branching & Merging / Lesson 2.3

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:

  1. Create and switch to a new branch: git checkout -b feature
  2. Create a file and commit: echo "feature work" > feature.txt then git add feature.txt then git commit -m "Add feature"
  3. Switch back to main: git checkout main
  4. Notice that feature.txt is gone — it only exists on the feature branch!

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.

🎯

Goal

Create a branch 'feature', switch to it, make a commit, then switch back to main

Terminal
$

No commits yet. Run `git init` and create your first commit.