Data report"State of code review 2024" is now liveRead the full report

Creating a new 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.


A branch in Git allows you to diverge from the main line of development and work independently, without affecting other parts of the project. Here, we'll explore how to create a new branch in Git, including various commands and best practices.

In Git, branches are essentially pointers to snapshots of your changes. When you create a branch, you create a new pointer to the current commit. This allows you to move forward with your own development without disturbing the main workflow.

Before creating a new branch, it's a good idea to know where you're branching from. Use the following command to see your current branch and all existing branches:

Terminal
git branch

This command will list all the branches in your repository and mark the current branch with an asterisk (*).

To create a new branch, use the git branch command followed by the name of the new branch. For example, to create a branch named feature-x:

Terminal
git branch feature-x

This command creates a new branch called feature-x but does not switch to it. The new branch is a copy of the branch you were on when you ran the command.

After creating a new branch, you need to switch to it to start making changes. Use the git checkout command to switch branches:

Terminal
git checkout feature-x

Alternatively, you can combine the creation and switching of branches into a single command with git checkout -b:

Terminal
git checkout -b feature-x

This command creates the new branch feature-x and switches to it immediately.

If you're working with a remote repository and want to make your new branch available to others, you need to push it to the remote. Use the following command to push the branch:

Terminal
git push -u origin feature-x

This command pushes the feature-x branch to the remote named origin and sets the upstream, which links your local branch to the remote branch.

  • Naming branches: Use descriptive names for your branches. For example, feature-add-login, bugfix-header, or refactor-authentication.
  • Keeping branches small and focused: Smaller branches are easier to manage and merge than larger ones.
  • Regularly pulling in changes from the main branch: To avoid conflicts, regularly pull changes from the main branch into your feature branch.

For information, see this guide on how to create a new branch in Git from a specific commit.

Graphite
Git stacked on GitHub

Stacked pull requests are easier to read, easier to write, and easier to manage.
Teams that stack ship better software, faster.

Or install our CLI.
Product Screenshot 1
Product Screenshot 2