Live streamJoin us for "State of code review 2024" on July 18thRegister today

How to checkout a branch in Git

Kenny DuMez
Kenny DuMez
Graphite software engineer


Note

This guide explains this concept in vanilla Git. For Graphite documentation, see our CLI docs.


Checking out a branch in Git allows developers to switch between different versions of their codebase. This guide will cover the necessary steps and commands to checkout a branch from Git in various scenarios.

The git checkout command is used to switch branches and restore working tree files. It's a way to point your local environment to a different snapshot of your project, represented by branches or commits.

Before checking out a branch, especially one that might have been added recently by another team member, it's important to update your list of remote branches:

Terminal
git fetch origin

This command retrieves the latest list of branches from the remote named origin.

To switch to the new branch run:

Terminal
git checkout <branch-name>

Replace <branch-name> with the name of the branch you want to switch to.

If you want to work with a branch that exists on the remote repository but not on your local machine, you can do so directly by:

Terminal
git checkout --track origin/<branch-name>

This command will automatically set up your local branch to track the remote branch, allowing you to push and pull changes without specifying the remote each time.

Sometimes, you might need to create a new branch based on another branch. This is common when starting a new feature that depends on the changes made in a different feature branch.

To create a new branch based on another branch, run:

Terminal
git checkout -b new-feature-branch existing-feature-branch

This creates and checks out new-feature-branch based on existing-feature-branch.

There are scenarios where you might need just one file or a few files from another branch without switching the entire branch. This can be done with:

Terminal
git checkout <branch-name> -- <path-to-file>

Replace <branch-name> with the branch from which you want to fetch the file, and <path-to-file> with the path to the file you need.

  • Be cautious with changes in the working directory: Changes in your working directory that have not been committed will be carried over when you switch branches. This can lead to conflicts or unexpected behavior. Commit or stash your changes before switching branches.
  • Use git fetch regularly: Keeping your local copy of the remote up-to-date helps avoid conflicts and errors when checking out branches.

For further reading see the official Git documentation.

Stay unblocked. Ship faster.
Experience the new developer workflow - create, review, and merge code continuously. Get started with one command.
Get started

Give your PR workflow
an upgrade today

Stack easier | Ship smaller | Review quicker

Or install our CLI.
Product Screenshot 1
Product Screenshot 2