← Back to Git Course | Chapter 3: Branching | Lesson 3 of 9

Git checkout Command

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

bash
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

bash
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

bash
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

bash
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

bash
git checkout main

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.