Git Branch Explained with Examples (Create, Switch, Delete Branches)

Git Branch Explained with Examples (Create, Switch, Delete Branches)

What is a Git Branch

A Git branch is an independent line of development within a Git repository. Branches allow developers to work on new features, bug fixes, or experiments without affecting the main production code.

When you create a branch, Git simply creates a new pointer to a commit. From that point onward, any new commits you make will belong to that branch. This makes branching extremely lightweight and fast in Git.

Branches are widely used in collaborative development environments because they allow multiple developers to work on different parts of a project simultaneously without interfering with each other's work.

Typical examples include:

  • Creating a feature branch to develop a new functionality.
  • Creating a bugfix branch to resolve an issue.
  • Creating a hotfix branch to patch a production problem quickly.

Once the work on a branch is complete, it can be merged back into the main branch. You can learn more about this process in our Git Merge Examples guide.

Why Git uses branches

Git branches exist to support parallel development. Instead of making all changes directly on the main branch, developers can create separate branches for different tasks.

Key advantages include:

  • Safe experimentation without affecting production code
  • Parallel development by multiple developers
  • Easy rollback if something breaks
  • Clean and organized development workflow

For example, a team may use branches such as:

  • feature-login
  • bugfix-payment
  • hotfix-security

Each branch represents a specific development task.

Difference between branch and commit

A commit represents a snapshot of changes in the repository at a specific point in time. For tips on writing better history, check out our Git Commit Message Guide.

A branch, on the other hand, is simply a pointer to a commit.

ConceptDescription
CommitSnapshot of repository changes
BranchPointer that references the latest commit in a development line

For example:

text
A --- B --- C (main)
           \
            D --- E (feature)

In this diagram:

  • C is the latest commit in the main branch
  • E is the latest commit in the feature branch

Default branch in Git (main vs master)

Traditionally, Git repositories used master as the default branch name.

However, modern Git platforms such as GitHub and GitLab now use main as the default branch name.

Branch NameMeaning
masterTraditional default branch
mainModern default branch

Both represent the primary branch of development.

You can check the default branch using:

bash
git branch

The active branch will appear with an asterisk *.


Git Branch Workflow Explained

Understanding the Git branch workflow is important when collaborating with other developers or managing complex projects.

Git branches allow developers to create isolated development environments inside the same repository.

A typical Git workflow looks like this:

  1. Clone repository using git clone
  2. Create a feature branch
  3. Make commits
  4. Push branch to remote repository
  5. Create pull request
  6. Merge changes into main branch

This workflow keeps the main branch stable while allowing multiple features to be developed simultaneously.

How branching works in Git internally

Internally, Git stores branches as references to commits.

When you create a branch, Git does not copy files. Instead, it simply creates a pointer to the latest commit.

For example:

text
A --- B --- C (main)

If you create a new branch:

bash
git branch feature-login

Git creates another pointer:

text
A --- B --- C (main)
           \
            (feature-login)

Once you start committing changes in the new branch, the branch pointer moves forward.

text
A --- B --- C (main)
           \
            D --- E (feature-login)

Understanding HEAD pointer in Git

In Git, the HEAD is a special pointer that indicates the currently active branch.

For example:

text
HEAD -> main

This means any new commit will be added to the main branch.

You can check the current branch using:

bash
git branch

Example output:

text
* main
  feature-login

The asterisk indicates the branch currently referenced by HEAD.

Visualizing Git branch history

You can visualize Git branch history using:

bash
git log --oneline --graph --all

Example output:

text
* e9c32f3 feature-login commit
* 7ab1d12 add login UI
| * 1c84a22 bugfix commit
|/
* b3f1c92 initial commit

Git Branch Command Syntax

The git branch command is used to create, list, rename, and delete branches in a Git repository.

Basic syntax:

bash
git branch [options] [branch-name]

Without any arguments, the command lists all local branches.

Basic git branch syntax

List branches:

bash
git branch

Create new branch:

bash
git branch feature-login

Delete branch:

bash
git branch -d feature-login

Rename branch:

bash
git branch -m new-branch-name

Important git branch flags and options

Some commonly used flags include:

OptionDescription
-aList all branches (local + remote)
-rList remote branches
-dDelete branch
-DForce delete branch
-mRename branch
-vvShow branch tracking information

Example:

bash
git branch -a

Displays both local and remote branches.


Git Branch Commands Quick Reference Table

Common git branch commands cheat sheet

TaskCommand
List branchesgit branch
List remote branchesgit branch -r
List all branchesgit branch -a
Create branchgit branch branch-name
Create and switch branchgit checkout -b branch-name
Switch branchgit checkout branch-name

Frequently used git branch options

ActionCommand
Delete branchgit branch -d branch-name
Force delete branchgit branch -D branch-name
Rename branchgit branch -m new-name
Push branch to remotegit push origin branch-name
Delete remote branchgit push origin --delete branch-name

List and Inspect Git Branches

Before creating or modifying branches, it is important to inspect the existing branches in your repository. Git provides several commands to list local branches, remote branches, and view commit information associated with each branch.

List local branches

To display all local branches in the current repository, use the following command:

bash
git branch

Example output:

text
* main
  feature-login
  bugfix-payment

The asterisk (*) indicates the currently active branch.

List remote branches

To view branches that exist in the remote repository, use:

bash
git branch -r

Example output:

text
origin/main
origin/feature-login
origin/hotfix-security

Remote branches are prefixed with the remote name (commonly origin).

List all branches (local + remote)

To display both local and remote branches, run:

bash
git branch -a

Example output:

text
* main
  feature-login
  remotes/origin/main
  remotes/origin/feature-login

This command is useful when verifying whether a branch exists locally or only on the remote repository.

Show last commit of each branch

You can display the latest commit associated with each branch using:

bash
git branch -v

Example output:

text
* main           a34f2c1 Update README
  feature-login  91c4b3a Add login functionality

For more detailed information including upstream tracking:

bash
git branch -vv

Create a Git Branch

Create branch using git branch

To create a new branch without switching to it:

bash
git branch feature-login

This creates the branch but keeps you on the current branch.

Verify the branch:

bash
git branch

Create branch and switch using git switch

Modern Git versions recommend using the git switch command to create and switch branches.

bash
git switch -c feature-dashboard

Example output:

text
Switched to a new branch 'feature-dashboard'

Create branch using git checkout -b

An older but still widely used method:

bash
git checkout -b feature-api

This command:

  1. Creates the branch
  2. Switches to the new branch immediately

Create branch from another branch

Sometimes you may want to create a branch based on a different branch instead of the current one.

Example:

bash
git checkout main
git branch feature-report

Or directly:

bash
git switch -c feature-report main

This creates feature-report from the latest commit of main.

Create branch from specific commit

You can create a branch from a specific commit in the repository history.

First identify the commit hash:

bash
git log --oneline

Example output:

text
c19e2d3 Fix login bug
8a1d3c9 Add authentication module

Create branch from the commit:

bash
git branch hotfix-auth 8a1d3c9

Now the new branch points to that commit.


Switch Between Git Branches

Switch branch using git switch

The recommended modern command:

bash
git switch feature-login

Example output:

text
Switched to branch 'feature-login'

Switch branch using git checkout

Older Git versions use the checkout command:

bash
git checkout feature-login

This performs the same operation but switch is preferred for clarity.

Verify current active branch

To verify the active branch:

bash
git branch

Example output:

text
main
* feature-login
bugfix-payment

The branch with the * symbol is the active branch.

You can also check using:

bash
git status

Example output:

text
On branch feature-login

Create Remote Git Branch

Push local branch to remote

To push a local branch to the remote repository, you can use git push.

bash
git push origin feature-login

This creates a remote branch called feature-login.

Set upstream tracking branch

To link the local branch with the remote branch:

bash
git push -u origin feature-login

After setting the upstream branch, you can simply run:

bash
git push

or

bash
git pull

without specifying the branch name.

Verify remote branch creation

To verify that the branch exists on the remote repository:

bash
git branch -r

Example output:

text
origin/main
origin/feature-login

Alternatively, fetch the latest remote references:

bash
git fetch --all
git branch -a

This confirms that the branch exists both locally and remotely.


Track Remote Branch

When collaborating with other developers, you may need to work on a branch that exists only on the remote repository. Git allows you to check out that branch locally and configure it to track the remote branch automatically.

Checkout remote branch locally

If a branch exists on the remote repository but not locally, you can create a local copy using git checkout remote branch:

bash
git checkout -b feature-login origin/feature-login

Example output:

text
Branch 'feature-login' set up to track remote branch 'feature-login' from 'origin'.
Switched to a new branch 'feature-login'

A more modern approach using git switch:

bash
git switch --track origin/feature-login

This creates a local branch that tracks the remote branch.

Set upstream tracking manually

If you already have a local branch but it does not track a remote branch, you can set tracking manually.

bash
git branch --set-upstream-to=origin/feature-login

Alternatively:

bash
git branch -u origin/feature-login

Once tracking is configured, Git will automatically know which remote branch to push and pull from.

Verify tracking configuration

To check the upstream tracking status:

bash
git branch -vv

Example output:

text
* feature-login 91c4b3a [origin/feature-login] Add login functionality
  main          a34f2c1 Update README

The square brackets indicate the remote branch being tracked.


Rename Git Branch

Rename current branch

If you want to rename the branch you are currently working on:

bash
git branch -m new-branch-name

Example:

bash
git branch -m feature-authentication

This renames the current branch.

Rename another branch

To rename a branch that is not currently checked out:

bash
git branch -m old-branch-name new-branch-name

Example:

bash
git branch -m feature-login feature-authentication

Rename remote branch safely

Renaming a remote branch requires multiple steps.

Step 1: Rename locally

bash
git branch -m new-branch-name

Step 2: Delete old remote branch

bash
git push origin --delete old-branch-name

Step 3: Push new branch

bash
git push origin new-branch-name

Step 4: Set upstream tracking

bash
git push -u origin new-branch-name

Merge Git Branch

Merge feature branch into main

First switch to the target branch:

bash
git switch main

Then merge the feature branch:

bash
git merge feature-login

Example output:

text
Updating a34f2c1..91c4b3a
Fast-forward

Fast forward vs non fast forward merge

Git can perform two types of merges.

Fast-forward merge

Occurs when the target branch has not diverged.

text
A --- B --- C (main)
           \
            D --- E (feature)

After merge:

text
A --- B --- C --- D --- E (main)

Non fast-forward merge

Occurs when both branches have independent commits.

Git creates a merge commit to combine histories.

Verify merge history

To view merge history:

bash
git log --oneline --graph --all

Example output:

text
*   f31c7e2 Merge branch 'feature-login'
|\
| * 91c4b3a Add login functionality
|/
* a34f2c1 Update README

Delete Git Branch

Branches should be removed after merging to keep the repository clean.

Delete local branch

To delete a local branch:

bash
git branch -d feature-login

Example output:

text
Deleted branch feature-login (was 91c4b3a).

Git prevents deletion if the branch contains unmerged changes.

Force delete local branch

If the branch contains unmerged commits:

bash
git branch -D feature-login

This forces the deletion.

Delete remote branch

To delete a branch from the remote repository:

bash
git push origin --delete feature-login

Example output:

text
To github.com:user/repo.git
 - [deleted] feature-login

Verify branch deletion

Check remaining branches:

bash
git branch

Check remote branches:

bash
git branch -r

Recover Deleted Git Branch

If a branch is deleted accidentally, Git still retains commit history, allowing recovery.

Recover branch using git reflog

Git maintains a log of recent actions called the reflog, which can be inspected using git reflog.

bash
git reflog

Example output:

text
91c4b3a HEAD@{0}: commit: Add login functionality
a34f2c1 HEAD@{1}: checkout: moving from main to feature-login

Find the commit hash associated with the deleted branch.

Restore branch from commit history

Create a new branch from the commit:

bash
git branch feature-login-recovered 91c4b3a

Switch to the restored branch:

bash
git switch feature-login-recovered

Your deleted branch is now restored.


Create Branch From Stash

Git stash allows you to temporarily save changes without committing them using git stash.Git stash allows you to temporarily save changes without committing them.

Save changes using git stash

To store current changes:

bash
git stash

Example output:

text
Saved working directory and index state WIP on feature-login

Create branch from stash

You can directly create a branch from the stashed changes.

bash
git stash branch feature-temp

This command:

  1. Creates a new branch
  2. Applies the stashed changes
  3. Removes the stash entry

Apply stash to new branch

Alternatively, apply stash manually.

First create a branch:

bash
git switch -c feature-temp

Then apply stash:

bash
git stash apply

If the changes are no longer needed in stash:

bash
git stash drop

This workflow is useful when switching tasks quickly during development.


Git Branch vs Git Checkout vs Git Switch

Git provides multiple commands to work with branches, and understanding the difference between git branch, git checkout, and git switch is important for managing branches effectively.

Difference between git branch and git checkout

The git branch command is used primarily to create, list, rename, or delete branches, but it does not automatically switch to the newly created branch.

Example:

bash
git branch feature-login

This command creates the branch but keeps you on the current branch.

To switch to the new branch, you must run:

bash
git checkout feature-login

Alternatively, you can create and switch in one step:

bash
git checkout -b feature-login

Summary:

CommandPurpose
git branchCreate or manage branches
git checkoutSwitch between branches or restore files
git checkout -bCreate and switch branch

Why git switch was introduced

The git switch command was introduced in Git 2.23 to simplify branch switching.

Previously, git checkout handled multiple tasks such as:

  • Switching branches
  • Restoring files
  • Creating branches

This made the command confusing for beginners.

To solve this problem, Git introduced two separate commands:

CommandPurpose
git switchSwitch between branches
git restoreRestore files

Example of switching branch:

bash
git switch feature-login

Create and switch branch:

bash
git switch -c feature-login

This improves command clarity and reduces mistakes.

When to use each command

The following table summarizes when to use each command.

TaskRecommended Command
Create branchgit branch
Create and switch branchgit switch -c
Switch branchesgit switch
Older Git versionsgit checkout
Restore filesgit restore

For modern Git workflows, it is recommended to prefer git switch over git checkout when working with branches.


Frequently Asked Questions

1. What is a Git branch?

A Git branch is an independent line of development that allows developers to work on features, bug fixes, or experiments without affecting the main codebase. Each branch points to a commit and moves forward as new commits are added.

2. How do I create a new branch in Git?

You can create a branch using git branch branch-name. To create and switch to the new branch immediately, use git switch -c branch-name or git checkout -b branch-name.

3. How do I switch between Git branches?

To switch branches, use git switch branch-name. Older Git versions use git checkout branch-name. The currently active branch will receive new commits.

4. How do I delete a Git branch?

To delete a local branch use git branch -d branch-name. To delete a remote branch use git push origin --delete branch-name.

5. What is the difference between git branch and git checkout?

The git branch command is used to create and manage branches, while git checkout is used to switch branches or restore files. Modern Git versions recommend using git switch for branch switching.

6. How do I see all branches in Git?

Use git branch to list local branches. To see remote branches run git branch -r. To display both local and remote branches use git branch -a.

7. How do I recover a deleted Git branch?

You can recover a deleted branch using git reflog to find the last commit reference and then recreate the branch using git branch branch-name <commit-hash>.

Summary

Git branching is one of the most powerful features that enables developers to work on multiple lines of development within the same repository.

In this guide, we explored several important Git branch operations including:

  • Understanding Git branch concepts
  • Listing and inspecting branches
  • Creating new branches
  • Switching between branches
  • Tracking remote branches
  • Renaming branches
  • Merging branches
  • Deleting local and remote branches
  • Recovering deleted branches
  • Creating branches from stash

By organizing your workflow around branches, you can safely develop features, fix bugs, and collaborate with other developers without affecting the main production code. For common issues, see cannot delete checked-out branch error.


Official Documentation

You can learn more about Git branching from the official Git documentation:

Deepak Prasad

Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels across development, DevOps, networking, and security, delivering robust and efficient solutions for diverse projects.