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

Git Branch Introduction

A branch is like making a copy of your story to try a wild new ending. You can play with it safely while the original story stays untouched.
Syntax
bash
git branch branch_name
git switch branch_name

What is a Git Branch?

A branch is Git's mechanism for an independent line of development -- under the hood it's just a movable pointer to a commit, which is why creating one is instant and cheap, letting you experiment freely without risking your stable code.

Example: What is a Git Branch?

bash
git branch feature-login

Why Use Branches?

Branches let separate pieces of work happen in isolation: one developer builds a feature, another fixes a bug, and neither set of unfinished changes can accidentally break what's running in production until it's deliberately merged in.

Example: Why Use Branches?

bash
git branch bugfix-header
git branch feature-payment

The Default Branch

Every repository starts with one default branch -- conventionally named main (or the older master) -- which by convention represents the project's current stable, deployable state, even though Git treats it as just another branch technically.

Example: The Default Branch

bash
git branch
# * main

Local vs Remote Branches

A local branch exists only on your own machine until you push it; a remote branch is one hosted on a server like GitHub. You fetch remote branches to see what teammates have done before deciding whether to merge those changes locally.

Example: Local vs Remote Branches

bash
git branch
git branch -r

Basic Branch Workflow

The everyday branch workflow is: create a branch for your task, switch onto it, commit your changes there, merge those commits back into main once finished, then delete the now-unneeded branch to keep the repository tidy.

Example: Basic Branch Workflow

bash
git branch feature-x
git checkout feature-x
git commit -m "Add feature"
git checkout main
git merge feature-x
git branch -d feature-x
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. Thinking a branch is a full copy of the project, when it is a lightweight pointer to a commit.
  2. Creating a branch with git branch feature and assuming you are now working on it, when you stay on the current branch until you switch.
  3. Committing new work to main by accident because the current branch was not checked first.

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.