Blog Details

Home Blog Details

Git Branching and Merging Explained with Practical Examples

WEB DEVELOPMENT 11 Nov 2026 By Well Spring Talent Team

Quick Answer: What Are Git Branching and Merging?

Git branching allows developers to create separate lines of development within the same repository. Each branch provides an independent workspace for developing a feature, fixing a bug or experimenting without directly changing another branch.

Git merging combines changes from one branch into another.

For example, a developer working on a website can create a branch called feature/contact-form, build the contact form independently and merge the completed work into main after testing.

The basic workflow is:

  1. Create a new branch using git switch -c feature-name.
  2. Make code changes and save them using Git commits.
  3. Switch to the target branch using git switch main.
  4. Combine the changes using git merge feature-name.
  5. Test the application and push the updated branch to the remote repository.

Understanding these operations helps developers collaborate, organise code changes and maintain a reliable development history.

Introduction

Imagine working on a Laravel application where the existing website is running correctly, but a new customer registration feature needs to be developed. At the same time, another developer is updating the dashboard, and a third person is fixing an issue with the login page.

If everyone makes changes directly to the same codebase without a proper workflow, coordinating updates becomes difficult. One developer's unfinished code may affect another person's work, and identifying the source of a problem can become time-consuming.

This is one of the reasons developers use Git branching and merging.

Git is a distributed version control system that records changes to files and helps developers manage different versions of a project. Branching allows developers to work on separate tasks, while merging brings completed changes together.

Whether you are developing a website, building a mobile application or maintaining a software project, understanding these concepts is an important part of professional development.

This guide explains how Git branches work, how to create and merge them, how to resolve conflicts and when to use merging instead of rebasing.

1. What Is a Git Branch?

A Git branch represents an independent line of development within a repository.

When you create a Git repository, it normally begins with a default branch, commonly named main. Developers can create additional branches from this branch to work on separate features or tasks.

For example, a website development project may have the following branches:

  • main – Contains the primary project code.
  • feature/user-registration – Contains changes for a registration feature.
  • feature/admin-dashboard – Contains dashboard development work.
  • bugfix/login-error – Contains a correction for a login issue.

Each branch can contain its own commits. Developers can move between branches without creating separate copies of the entire project manually.

How Git Branches Work Internally

A Git branch is essentially a movable reference to a commit. When you create a new branch, Git creates a new reference pointing to the current commit.

As you make additional commits on that branch, its reference advances to the latest commit. Other branches can continue pointing to their own commits.

This structure allows different development tasks to progress independently while sharing a common repository history.

Why Do Developers Use Git Branching?

Branching offers several practical advantages:

Independent Development: Developers can work on new features without directly modifying the main development line.

Safer Experimentation: New approaches can be tested without immediately affecting the primary codebase.

Parallel Collaboration: Multiple developers can work on separate tasks at the same time.

Organised Code Changes: Each branch can represent a particular feature, bug fix or improvement.

Easier Code Reviews: Teams can review a focused set of changes before integrating them into the main project.

2. Understand the Basic Git Branching Structure

Before exploring commands, understand how branches develop from a shared commit history.

Suppose a developer has created an initial website and committed the basic homepage.

The repository initially looks like this:

A --- B --- C
            |
           main

Here, A, B and C represent commits, and main points to the latest commit.

The developer now wants to build a contact form. Instead of making the changes directly in main, a new branch is created.

A --- B --- C
            |
           main
            \
             D --- E
                   |
              feature/contact-form

The new branch starts from commit C. The developer can now create commits D and E without moving the main branch.

If another developer works on the dashboard, a separate branch can be created for that task.

The branches can later be combined when the changes are ready.

This is the foundation of Git Branching and Merging.

3. How to Create a Branch in Git

Creating a branch is one of the first operations developers should learn when working with Git.

Before creating a branch, check your current repository status.

git status

To display the existing local branches, run:

git branch

The currently active branch is marked with an asterisk.

Create a New Branch

Use the following command:

git branch feature/contact-form

This creates a branch called feature/contact-form, but it does not automatically switch to that branch.

To start working on it, run:

git switch feature/contact-form

Create and Switch to a Branch in One Command

A more convenient approach is:

git switch -c feature/contact-form

This command creates the branch and switches to it immediately.

For older Git workflows, developers may also encounter:

git checkout -b feature/contact-form

Both approaches can create and switch to a new branch. The git switch command provides a more focused interface for branch switching.

Verify the Active Branch

Run:

git branch

Example output:

  main
* feature/contact-form

The asterisk indicates that feature/contact-form is currently active.

4. Essential Git Branch Commands Every Beginner Should Know

Understanding common branch commands makes daily development easier and helps developers navigate repositories confidently.

Git Command Purpose
git branch Lists local branches
git branch -a Lists local and remote-tracking branches
git branch feature-name Creates a new branch
git switch branch-name Switches to an existing branch
git switch -c branch-name Creates and switches to a branch
git branch -d branch-name Deletes a branch if Git considers it safely merged
git branch -D branch-name Force-deletes a local branch
git branch -m new-name Renames the current branch
git status Displays the current branch and working-tree changes
git log --oneline --graph --all Displays a compact commit history with branch relationships

Switch Between Branches

To return to the main branch:

git switch main

To return to the contact form branch:

git switch feature/contact-form

Git updates the working directory to reflect the selected branch.

Before switching, check for uncommitted changes. Depending on the files involved, Git may prevent the switch to avoid overwriting your work.

Delete a Completed Branch

After a feature has been merged and is no longer required locally, you can delete its branch:

git branch -d feature/contact-form

Use -d for normal cleanup because Git checks whether the branch is safely merged.

The force-delete option:

git branch -D feature/contact-form

should be used carefully because it can delete a branch even when its changes have not been merged.

Deleting a branch does not automatically delete the commits that are still reachable through other references, but unmerged work may become difficult to recover.

5. Git Branching Tutorial: A Practical Feature Development Example

Consider a training institute website that already contains a homepage, course listing page and contact page.

The development team wants to add an online course enquiry form.

Instead of modifying the main branch directly, the developer follows a feature-based workflow.

Step 1: Open the Project Repository

Navigate to the project directory:

cd training-website

Check the current branch:

git branch

Assume the active branch is main.

Step 2: Create a Feature Branch

Create a separate branch for the enquiry form:

git switch -c feature/course-enquiry

The developer can now work on the new functionality independently.

Step 3: Create the Required Files

For example, a Laravel project may contain:

resources/
    views/
        course-enquiry.blade.php

public/
    css/
        enquiry.css

routes/
    web.php

The developer adds the form interface, styles and required route changes.

Step 4: Review the Changes

Before saving the work, check which files have changed:

git status

To inspect the actual modifications:

git diff

This helps identify unintended edits before committing.

Step 5: Stage the Required Files

Add the files to Git's staging area:

git add resources/views/course-enquiry.blade.php
git add public/css/enquiry.css
git add routes/web.php

Alternatively, stage all current changes when you have reviewed them:

git add .

Step 6: Create a Commit

Save the changes in the branch history:

git commit -m "Add course enquiry form"

A commit records a snapshot of the staged changes.

Step 7: Test the Feature

Verify that the enquiry form displays correctly, validates the required fields and handles submissions as expected.

Testing should happen before the feature is integrated into the main branch.

Step 8: Merge the Completed Feature

Once the feature is ready, switch to the target branch:

git switch main

Merge the feature branch:

git merge feature/course-enquiry

Git combines the changes from the feature branch into the current branch, provided the merge can be completed successfully.

This example demonstrates how a developer can build a feature independently and integrate it after testing.

6. Git Merge Explained: How Branches Come Together

Git merging combines the development history of one branch with another.

The command is:

git merge branch-name

An important detail is that Git merges the specified branch into the currently active branch.

For example:

git switch main
git merge feature/course-enquiry

Here, feature/course-enquiry is merged into main.

Types of Git Merge

Git commonly performs different merge operations depending on the relationship between the branch histories.

1. Fast-Forward Merge

A fast-forward merge occurs when the target branch has not advanced independently since the feature branch was created.

For example:

Before:

A --- B --- C --- D
      main        feature

If main still points to commit B, merging the feature branch simply moves the main reference forward.

After:

A --- B --- C --- D
                  |
                 main
                 feature

No additional merge commit is required.

This approach is possible because the target branch can move forward without combining separate lines of development.

2. Three-Way Merge

A three-way merge is used when both branches have developed independently after sharing a common starting commit.

Example:

            C --- D
           /       \
A --- B ---         --- M
           \       /
            E --- F

Here:

  • B is the common ancestor.
  • D represents the latest commit on one branch.
  • F represents the latest commit on another branch.
  • M represents the resulting merge commit.

Git compares the common ancestor with the two branch tips to combine their changes.

A merge commit records both branch histories as parents.

Force a Merge Commit

Sometimes a team wants to preserve a visible merge commit even when a fast-forward merge is possible.

Use:

git merge --no-ff feature/course-enquiry

This prevents a fast-forward merge and creates a merge commit when the merge succeeds.

Whether to use this option depends on the team's preferred history and review workflow.

7. How to Resolve Git Merge Conflicts

A merge conflict occurs when Git cannot automatically combine changes from different branches.

This commonly happens when two developers modify the same part of a file differently.

Practical Merge Conflict Example

Imagine two developers working on the same website.

The first developer changes the homepage heading on the feature/homepage branch:

<h1>Explore Our Professional Courses</h1>

The second developer changes the same heading on the feature/marketing-banner branch:

<h1>Build Your Future with Practical Training</h1>

When the branches are merged, Git may not know which version should be retained.

It pauses the merge and marks the conflicting section.

Step 1: Identify the Conflict

Run:

git status

Git displays the files that require conflict resolution.

Step 2: Open the Conflicting File

A conflicted file may contain markers similar to these:

<<<<<<< HEAD
<h1>Explore Our Professional Courses</h1>
=======
<h1>Build Your Future with Practical Training</h1>
>>>>>>> feature/marketing-banner

The section above ======= represents the current branch's version, while the section below it represents the incoming branch's version.

Step 3: Choose the Correct Content

The developer must understand the intended design and decide which content should remain.

For example, the final version might be:

<h1>Build Your Future Through Professional Courses</h1>

Remove all conflict markers and save the file.

If both changes are useful, combine them into a suitable final implementation rather than blindly selecting one version.

Step 4: Mark the Conflict as Resolved

Stage the corrected file:

git add index.html

Step 5: Complete the Merge

Run:

git merge --continue

Alternatively, after staging the resolved files, git commit can be used to complete a merge when Git requires a merge commit.

Cancel a Merge When Necessary

If you decide not to continue with the current merge, use:

git merge --abort

This attempts to return the working tree to its pre-merge state. It is best to commit or stash unrelated work before starting a merge.

Important: A merge conflict is not necessarily a sign of a broken repository. It is a situation where a developer needs to make a decision about how independently developed changes should be combined.

8. Git Merge vs Rebase: What Is the Difference?

Git merge and Git rebase are two different ways to integrate changes from one branch into another.

Both can help developers update their work, but they produce different commit histories.

What Is Git Rebase?

Rebase takes the commits from your current branch and replays them on top of another branch.

For example, suppose the feature branch was created from an older version of main, but main has received additional commits.

A developer can update the feature branch using:

git switch feature/course-enquiry
git rebase main

Git attempts to replay the feature branch's commits on top of the latest commit in main.

Visual Comparison

Before rebase:

       C --- D
      /
A --- B --- E --- F

Here, the feature branch contains commits C and D, while main has progressed through E and F.

After rebase:

A --- B --- E --- F --- C' --- D'

The feature commits are recreated on top of the updated main branch. Their commit identities change because they are new commits.

Git Merge vs Rebase Comparison

Aspect Git Merge Git Rebase
Main purpose Combines branch histories Replays commits on a new base
Commit history Preserves branch relationships Creates a more linear history
Merge commit May create one Does not create a merge commit for the rebase itself
Commit identities Existing commits are generally preserved Replayed commits receive new identities
Conflict handling Conflicts may be resolved during merging Conflicts may need to be resolved while replaying commits
Common use Integrating completed feature branches Updating a private feature branch before integration

When Should You Use Git Merge?

Use merge when you want to combine work while preserving the actual history of how branches developed.

It is useful for team collaboration, shared branches and workflows where merge commits provide valuable context.

When Should You Use Git Rebase?

Use rebase when you want to update your feature branch with the latest target branch changes and maintain a more linear history.

It is particularly useful for cleaning up local commits before sharing work.

An Important Rebase Safety Rule

Rebase changes commit history. Avoid rebasing commits that other developers have already based their work on unless the team has explicitly coordinated the operation.

Rewriting shared history can create confusion and require other contributors to repair their local branches.

For beginners, a sensible approach is to understand merging first and then learn rebase as an additional tool.

9. Git Workflow for Beginners: A Team Development Process

A Git workflow defines how developers create branches, save changes, review work and integrate completed features.

A common beginner-friendly approach is feature branching.

Step 1: Start from the Updated Main Branch

Before starting new work, update your local repository:

git switch main
git pull origin main

This retrieves the latest remote changes and integrates them into the local main branch according to the configured pull behaviour.

Step 2: Create a Feature Branch

Use a descriptive name:

git switch -c feature/student-dashboard

A good branch name makes it easier for team members to understand the purpose of the work.

Step 3: Develop and Commit Changes

Make the required modifications and check them:

git status
git diff

Stage and commit the work:

git add .
git commit -m "Create student dashboard layout"

Step 4: Push the Branch to the Remote Repository

Publish the branch:

git push -u origin feature/student-dashboard

The -u option sets the upstream tracking relationship, making later push and pull operations more convenient.

Step 5: Create a Pull Request or Merge Request

On a collaboration platform such as GitHub or GitLab, create a request to merge the feature branch into the target branch.

Other developers can review the changes, provide feedback and request improvements.

Step 6: Complete the Review and Testing

Resolve review comments, run relevant tests and ensure that the changes meet the project's requirements.

Step 7: Merge the Feature

After approval, merge the feature into the target branch using the team's chosen merge strategy.

Step 8: Clean Up the Branch

After successful integration, the remote feature branch can be deleted through the collaboration platform or command line.

To remove the local branch:

git switch main
git branch -d feature/student-dashboard

This workflow keeps development organised and provides a clear process for integrating changes.

10. Git Branch Naming Conventions and Best Practices

Consistent branch naming makes repositories easier to manage, especially when several developers work on the same project.

Common naming patterns include:

Branch Prefix Purpose Example
feature/ New functionality feature/course-filter
bugfix/ Bug correction bugfix/login-validation
hotfix/ Urgent production correction hotfix/payment-error
docs/ Documentation updates docs/api-guide
refactor/ Code restructuring refactor/user-service
test/ Testing-related work test/registration-flow

Best Practices for Branch Management

Create Focused Branches: Keep each branch related to one feature, issue or task. Avoid combining unrelated changes in a single branch.

Use Descriptive Names: Choose names that explain the purpose of the work rather than using vague labels such as new-branch or test1.

Commit Frequently: Create meaningful commits when logical units of work are complete. This makes changes easier to review and troubleshoot.

Keep Feature Branches Updated: Regularly integrate changes from the target branch to reduce the difficulty of handling large differences later.

Review Before Merging: Check the code, run tests and examine the changes before integrating them.

Avoid Direct Changes to Protected Branches: Teams can use repository permissions and branch protection rules to control how changes enter important branches.

Remove Unnecessary Branches: Clean up completed branches to keep the repository easier to navigate.

Communicate with Team Members: Inform other developers when a change affects shared files, application architecture or common development workflows.

11. Common Git Branching and Merging Mistakes

Beginners often understand the commands but make mistakes when applying them to actual projects.

Here are some situations worth avoiding.

Creating a Branch from the Wrong Starting Point

A new branch is created from the currently checked-out commit. If you accidentally create it from an outdated or unrelated branch, it may include unexpected changes.

Check your current branch before creating a new one:

git branch --show-current

Merging in the Wrong Direction

The command git merge feature-name integrates the specified branch into the current branch.

If you are on the feature branch instead of main, the merge will happen in the opposite direction from what you intended.

Always check the active branch before merging.

Forgetting to Commit Changes

Uncommitted work can complicate branch switching and merging. Review your working tree and commit or stash changes when appropriate.

Using Force Delete Without Checking the Branch

The command git branch -D can remove an unmerged branch. Use it only when you are certain the work is no longer required or has been safely preserved.

Rebasing Shared Branches Without Coordination

Rebase rewrites commit history. Rewriting commits that teammates already depend on can create unnecessary problems.

Ignoring Merge Conflicts

Removing conflict markers without understanding the intended code can introduce bugs. Review both versions and test the final result.

Merging Without Testing

A merge can complete successfully while the application still contains functional errors. Run appropriate tests and verify important application workflows after integration.

12. Practical Git Branching Exercise for Beginners

The best way to understand branching and merging is to practise the entire process in a small project.

Create a sample repository and simulate the development of two independent features.

Exercise: Build a Simple Website

Start by creating a project:

mkdir git-practice
cd git-practice

git init

Create an index.html file:

<!DOCTYPE html>
<html>
<head>
    <title>Training Website</title>
</head>
<body>
    <h1>Welcome to Our Training Website</h1>
</body>
</html>

Save the initial version:

git add index.html
git commit -m "Create initial homepage"

Create the First Feature Branch

git switch -c feature/about-section

Add an About section to the homepage and commit it:

git add index.html
git commit -m "Add about section"

Create Another Feature Branch

Return to the main branch:

git switch main

Create a separate contact section branch:

git switch -c feature/contact-section

Add the contact section and commit it:

git add index.html
git commit -m "Add contact section"

Merge the Completed Features

Return to main:

git switch main

Merge the About section:

git merge feature/about-section

Then merge the Contact section:

git merge feature/contact-section

If both changes affect independent parts of the file, Git may combine them automatically. If they modify overlapping content, you may need to resolve a conflict.

Examine the Final History

Run:

git log --oneline --graph --all

This displays the commits and branch relationships in a compact graphical format.

Learning objective: By completing this exercise, beginners can practise repository creation, branch management, commits, switching, merging and history inspection without working on a production application.

Conclusion

Git branching and merging are essential skills for developers who work on websites, applications and collaborative software projects. Branching provides a controlled way to develop features independently, while merging brings completed changes together without losing the project's development history.

Beginners should start by understanding how branches work, practising commands such as git branch, git switch and git merge, and learning how to resolve simple conflicts. Once these operations become familiar, exploring rebase, pull requests and team-based workflows becomes much easier.

For anyone learning software development, regular Git practice is more valuable than memorising commands without understanding their purpose. Create small projects, experiment with separate branches and review the commit history to understand how changes move through a repository.

With consistent practice, Git becomes more than a tool for saving code. It becomes a reliable way to organise development, collaborate with others and maintain software projects with greater confidence.

Frequently Asked Questions

Git branching allows developers to create separate lines of development within a repository. Merging combines changes from one branch into another. Together, these operations help developers build features independently and integrate completed work into a shared codebase.

Use git switch -c branch-name to create a new branch and switch to it immediately. For example, git switch -c feature/login-page creates a branch named feature/login-page and makes it the active branch.

Git merge combines branch histories and may create a merge commit. Git rebase replays commits on top of another branch, creating a more linear history. Rebase changes commit identities, so it should be used carefully with shared branches.

Use git branch to display local branches. Use git branch -a to display local branches and remote-tracking branches. The currently active local branch is marked with an asterisk.

A merge conflict occurs when Git cannot automatically combine overlapping changes from different branches. Developers must inspect the affected files, choose or combine the correct changes, remove conflict markers, stage the resolved files and complete the merge.

Yes. After a branch has been successfully merged and is no longer needed, use git branch -d branch-name to delete the local branch. A remote branch can be deleted using git push origin --delete branch-name, provided you have the required permissions.

A simple feature branching workflow is a good starting point. Developers create a separate branch for each feature or bug fix, commit their changes, push the branch for review and merge it into the main branch after testing and approval.

Still Have Questions?

If you didn't find your answer here, feel free to reach out to us.

Contact

Your Local Destination for IT Training

We provide IT training, internships, and online learning for students in Trichy and across India.

IT Training Areas in Trichy

Thillai Nagar KK Nagar Srirangam Cantonment Woraiyur Tennur Karumandapam Edamalaipatti Pudur Puthur Crawford BHEL Township Ariyamangalam Kattur Ponmalai (Golden Rock) Vayalur Road Bharathidasan Salai Chathiram Bus Stand Palakkarai Subramaniapuram Sangiliyandapuram Trichy Airport Area Thiruverumbur Samayapuram Manachanallur Panjappur Navalpattu Central Bus Stand Trichy Railway Junction Gandhi Market Palpannai Anna Nagar Thiruvanaikoil TVS Tollgate Ponnagar Beemanagar Kallukuzhi Thuvakudi Pudukottai Road Thanjavur Road Karur Bypass Road

Online IT Training Across India

Can't attend classes in person? Explore online IT training opportunities with Well Spring Talent Solutions, designed to help learners develop practical technology skills from different locations across India.

Join Our WhatsApp Channel ๐Ÿ’ฌ

Join our WhatsApp community for internship updates, IT courses, placement support, and latest job opportunities.

Join Now

Our Branches

Visit our branches in Tiruchirappalli for IT training and career guidance.