0
0
GitHow-ToBeginner · 3 min read

How to Create a Branch in Git: Simple Steps

To create a new branch in Git, use the command git branch <branch-name>. To create and switch to the new branch immediately, use git checkout -b <branch-name> or git switch -c <branch-name>.
📐

Syntax

The basic syntax to create a branch is git branch <branch-name>. This creates the branch but keeps you on the current branch. To create and switch to the new branch in one step, use git checkout -b <branch-name> or the newer git switch -c <branch-name>.

  • <branch-name>: The name you want to give your new branch.
  • git branch: Creates a new branch without switching.
  • git checkout -b: Creates and switches to the new branch.
  • git switch -c: Modern command to create and switch to a branch.
bash
git branch <branch-name>
git checkout -b <branch-name>
git switch -c <branch-name>
💻

Example

This example shows how to create a branch named feature1 and switch to it immediately using the modern git switch command.

bash
$ git switch -c feature1
Switched to a new branch 'feature1'
$ git branch
  main
* feature1
Output
Switched to a new branch 'feature1' main * feature1
⚠️

Common Pitfalls

One common mistake is creating a branch but forgetting to switch to it, so you continue working on the old branch. Another is using git checkout without the -b flag, which switches branches but does not create a new one.

Wrong way (creates branch but stays on old branch):

bash
git branch feature1
# You are still on the old branch

# Right way to create and switch:
git checkout -b feature1
# or
git switch -c feature1
📊

Quick Reference

CommandDescription
git branch Create a new branch without switching
git checkout -b Create and switch to new branch (older method)
git switch -c Create and switch to new branch (recommended)

Key Takeaways

Use git switch -c <branch-name> to create and switch to a new branch in one step.
Creating a branch with git branch <branch-name> does not switch you to it automatically.
Avoid using git checkout without -b to prevent confusion between switching and creating branches.
Branch names should be clear and descriptive to keep your project organized.