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

Git checkout Command

git checkout is like walking into another room where a different copy of your project is set up. Your files change to match whichever branch you step into.
Syntax
bash
git checkout branch_name
git checkout -b new_branch_name
git checkout -- file_name

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using git checkout file.txt to discard changes and losing them permanently because there is no undo.
  2. Running git checkout otherbranch with uncommitted changes that conflict, and getting an error instead of switching.
  3. Checking out a commit hash and committing there, ending up in a detached HEAD state where new commits are easy to lose.

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.