15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
31.10.2024
1 +1

Working with Branches in Git: The Complete Guide for Developers

Git branching is one of the most powerful features in modern software development. It allows you to develop new features, fix bugs, and run experiments in complete isolation — without ever touching your stable production codebase. Whether you're a solo developer or part of a distributed team, mastering Git branches is essential to maintaining clean, professional workflows.

This comprehensive guide walks you through everything you need to know about Git branching: from understanding the core concepts to creating, switching, merging, and managing branches like a senior developer. If you're running your projects on a VPS Hosting environment with full root access, these workflows integrate seamlessly into your daily development pipeline.

What Is a Git Branch?

A branch in Git is essentially a lightweight, movable pointer to a specific commit in your project's history. When you initialize a repository, Git creates a default branch — typically called main or master — which represents your primary line of development.

When you create a new branch, you're spinning up an independent line of development that diverges from the current state of the codebase. Changes made on that branch do not affect any other branch until you explicitly merge them. This isolation is what makes branching so valuable: your main branch stays clean and deployable while work-in-progress lives safely elsewhere.

Think of branches as parallel universes for your code. Each one can evolve independently, and you control exactly when and how they come back together.

Why Git Branching Matters for Your Hosting Environment

If you're deploying applications on a server — whether that's a VPS Hosting plan or a Dedicated Servers environment — Git branching becomes even more critical. Here's why:

  • Stability: Your production branch (main) remains deployable at all times.
  • Team collaboration: Multiple developers can work on separate features simultaneously without stepping on each other's changes.
  • Safe experimentation: You can test risky changes on an isolated branch and simply delete it if things go wrong.
  • CI/CD integration: Branching strategies like GitFlow or trunk-based development pair perfectly with automated deployment pipelines running on your server.
  • Rollback capability: If a merge introduces a bug, you can revert cleanly without losing other work.

Hosting your Git repositories on a server with NVMe SSD storage and full root access means faster clone, fetch, and push operations — especially important when working with large repositories or multiple contributors.

Step 1: Checking Existing Branches

Before creating anything new, it's good practice to review what branches already exist in your repository. Use the following command:

git branch

This lists all local branches. The currently active branch is highlighted with an asterisk (*).

To also see remote branches, use:

git branch -a

To see remote branches only:

git branch -r

Understanding your existing branch landscape prevents naming conflicts and helps you stay oriented in complex projects.

Step 2: Creating a New Branch

There are several ways to create a new branch in Git, depending on your workflow.

Create a branch without switching to it:

git branch branch_name

Replace branch_name with a meaningful name that reflects the purpose of the branch. For example:

git branch feature/user-authentication

Create a branch and switch to it immediately (classic method):

git checkout -b branch_name

Example:

git checkout -b feature/user-authentication

Create and switch using the modern switch command (Git 2.23+):

git switch -c branch_name

Example:

git switch -c bugfix/login-redirect

The git switch command was introduced to make branch operations more intuitive and less ambiguous than the overloaded git checkout command. Both approaches work, but git switch is the recommended modern practice.

Step 3: Switching Between Branches

To move between existing branches, you have two options:

Classic method:

git checkout branch_name
git switch branch_name

Example — switching back to the main branch:

git switch main

Important: Before switching branches, make sure your working directory is clean. Either commit your changes or stash them using git stash, otherwise Git may refuse the switch or carry uncommitted changes into the new branch context.

git stash          # Save uncommitted changes temporarily
git switch main    # Switch branch
git stash pop      # Restore your stashed changes later

Step 4: Making Changes on a Branch

Once you're on the correct branch, your development workflow proceeds normally. Here's the standard cycle:

1. Edit or create files

Make your changes using your preferred editor or IDE.

2. Stage your changes

git add filename

Or stage all modified files at once:

git add .

3. Commit your changes

git commit -m "Add user authentication module"

Write clear, descriptive commit messages. A good commit message explains what changed and why — not just how. This becomes invaluable when reviewing history months later or onboarding new team members.

4. Push your branch to a remote repository

If you're collaborating with a team or backing up to a remote server:

git push origin branch_name

Example:

git push origin feature/user-authentication

If it's the first time pushing this branch, you may need to set the upstream:

git push --set-upstream origin feature/user-authentication

Step 5: Merging Branches

Once your feature or fix is complete and tested, it's time to merge it back into your target branch — typically main or develop.

Step-by-step merge process:

1. Switch to the target branch:

git switch main

2. Pull the latest changes from remote (important in team environments):

git pull origin main

3. Merge your feature branch:

git merge feature/user-authentication

If the merge is clean (no conflicts), Git will automatically create a merge commit or perform a fast-forward merge depending on the branch history.

Fast-forward vs. merge commit

  • Fast-forward merge: Occurs when the target branch has not diverged from the feature branch. Git simply moves the pointer forward. No merge commit is created.
  • Three-way merge: Occurs when both branches have diverged. Git creates a new merge commit that ties both histories together.

To always create a merge commit (useful for preserving branch history in project logs):

git merge --no-ff feature/user-authentication

Step 6: Resolving Merge Conflicts

Merge conflicts occur when the same lines in a file have been modified differently on two branches. Git cannot automatically determine which version to keep, so it asks you to resolve the conflict manually.

Identifying conflicts

When a conflict occurs, Git will output something like:

CONFLICT (content): Merge conflict in src/auth.js
Automatic merge failed; fix conflicts and then commit the result.

What a conflict looks like in a file

<<<<<<< HEAD
const loginUrl = '/api/v2/login';
=======
const loginUrl = '/api/v1/login';
>>>>>>> feature/user-authentication
  • Everything between <<<<<<< HEAD and ======= is the version from your current branch.
  • Everything between ======= and >>>>>>> feature/user-authentication is the incoming version.

Resolving the conflict

  1. Open the conflicting file in your editor.
  2. Decide which version to keep — or write a new version that combines both.
  3. Remove all conflict markers (<<<<<<<, =======, >>>>>>>).
  4. Save the file.

Completing the merge after resolution

git add src/auth.js
git commit -m "Resolve merge conflict in auth module"

Using a merge tool

For complex conflicts, a visual merge tool can be invaluable:

git mergetool

Popular tools include VS Code's built-in diff editor, vimdiff, meld, and kdiff3.

Step 7: Deleting Branches

Once a branch has been merged and is no longer needed, delete it to keep your repository clean and navigable.

Delete a local branch (safe — only works if already merged):

git branch -d branch_name

Example:

git branch -d feature/user-authentication

Force-delete a branch (even if unmerged):

git branch -D branch_name

Use -D with caution — it permanently discards any unmerged work on that branch.

Delete a remote branch:

git push origin --delete branch_name

Example:

git push origin --delete feature/user-authentication

Regularly pruning stale branches keeps your repository organized and prevents confusion in team environments.

Step 8: Viewing Branch History and Structure

To get a visual overview of your entire branch and commit history, use:

git log --oneline --graph --decorate --all

This produces a compact, ASCII-art graph showing:

  • All commits across all branches
  • Where each branch pointer currently sits
  • Merge points and divergences
  • Tags and HEAD position

Example output:

* a3f9c12 (HEAD -> main, origin/main) Merge branch 'feature/user-authentication'
|
| * 7b2e441 Add password hashing utility
| * 3d1a908 Create login endpoint
|/
* 9c4f017 Initial project setup

For a more detailed view of a specific branch:

git log branch_name --oneline

To compare two branches and see what commits exist in one but not the other:

git log main..feature/user-authentication --oneline

Step 9: Advanced Branching Techniques

Rebasing instead of merging

Rebasing is an alternative to merging that rewrites commit history to produce a cleaner, linear timeline:

git rebase main

This replays your feature branch commits on top of the latest main, eliminating the merge commit. The result is a cleaner history — but never rebase branches that have been pushed to a shared remote, as it rewrites history and causes problems for collaborators.

Cherry-picking specific commits

If you only need one specific commit from another branch rather than merging the entire branch:

git cherry-pick commit_hash

This is useful for applying a critical bug fix from a development branch directly to production without merging unfinished features.

Tracking remote branches

To set up a local branch that tracks a remote branch:

git checkout --track origin/branch_name

Or with the modern syntax:

git switch --track origin/branch_name

Git Branching Strategies for Production Environments

If you're managing a live application on a Dedicated Servers or VPS environment, adopting a formal branching strategy dramatically improves deployment reliability.

GitFlow

A structured workflow with dedicated branches for features, releases, and hotfixes:

  • main — production-ready code only
  • develop — integration branch for completed features
  • feature/* — individual feature branches
  • release/* — release preparation branches
  • hotfix/* — emergency production fixes

Trunk-Based Development

A simpler, high-velocity approach where all developers commit to main (the "trunk") frequently, using short-lived feature branches or feature flags to manage incomplete work. Favored by teams with robust CI/CD pipelines.

GitHub Flow

A lightweight variant: branch off main, open a pull request, review, merge. Simple and effective for smaller teams or projects with continuous deployment.

Best Practices for Git Branch Management

Following these conventions will keep your repositories clean, your team aligned, and your deployments predictable:

1. Use descriptive, structured branch names

Adopt a consistent naming convention that communicates purpose at a glance:

TypeExample
Featurefeature/user-authentication
Bug fixbugfix/login-redirect-loop
Hotfixhotfix/payment-gateway-crash
Releaserelease/v2.4.0
Experimentexperiment/graphql-migration

2. Keep branches short-lived

The longer a branch lives without merging, the greater the divergence from main and the higher the risk of painful merge conflicts. Aim to merge feature branches within days, not weeks.

3. Commit early and often

Small, frequent commits are easier to review, revert, and understand. Avoid massive "catch-all" commits that bundle dozens of unrelated changes.

4. Always pull before merging

Before merging a feature branch, pull the latest changes from main to minimize conflicts:

git pull origin main

5. Write meaningful commit messages

Follow the conventional commits format for consistency:

feat: add OAuth2 login support
fix: resolve null pointer in user profile loader
docs: update API authentication guide
refactor: simplify database connection pooling

6. Protect your main branch

On hosted Git platforms (GitHub, GitLab, Gitea), configure branch protection rules to require pull request reviews before merging into main. This prevents accidental direct pushes to production.

7. Automate with CI/CD

Integrate your Git workflow with a CI/CD pipeline that automatically runs tests on every branch push. Only branches that pass all tests should be eligible for merging. This pairs perfectly with a properly configured server environment — if you're hosting your own Git server or CI runner, a VPS Hosting plan with root access gives you complete control over your pipeline configuration.

Setting Up a Private Git Repository on Your Server

If you prefer to self-host your Git repositories rather than relying on third-party platforms, you can set up a bare Git repository directly on your server.

Initialize a bare repository on the server:

mkdir -p /srv/git/myproject.git
cd /srv/git/myproject.git
git init --bare

Clone it from your local machine:

git clone user@yourserver.com:/srv/git/myproject.git

Push branches to it just like any remote:

git push origin feature/new-dashboard

Self-hosting your Git repositories gives you complete privacy, no storage limits imposed by third-party platforms, and full control over access permissions. Pair this with SSL Certificates to encrypt traffic between your developers and the server, and consider setting up SSH key authentication for secure, password-free access.

For teams that need a full-featured Git hosting interface, tools like Gitea or GitLab CE can be installed on your VPS in under an hour, giving you pull requests, issue tracking, and CI/CD pipelines — all self-hosted on infrastructure you control.

Quick Reference: Essential Git Branch Commands

TaskCommand
List local branchesgit branch
List all branches (including remote)git branch -a
Create a new branchgit branch branch_name
Create and switch to new branchgit switch -c branch_name
Switch to existing branchgit switch branch_name
Merge a branch into currentgit merge branch_name
Merge with explicit merge commitgit merge --no-ff branch_name
Rebase onto another branchgit rebase main
Delete merged local branchgit branch -d branch_name
Force delete local branchgit branch -D branch_name
Delete remote branchgit push origin --delete branch_name
View graphical branch historygit log --oneline --graph --decorate --all
Stash uncommitted changesgit stash
Apply stashed changesgit stash pop
Cherry-pick a specific commitgit cherry-pick commit_hash

Conclusion

Git branching is not just a technical feature — it's a professional discipline that separates organized, scalable development from chaotic, fragile codebases. By mastering the commands and strategies covered in this guide, you'll be equipped to manage complex projects with confidence, collaborate effectively with teammates, and deploy with predictability.

The key principles to carry forward:

  • Isolate work in dedicated branches to protect your main branch at all times.
  • Name branches descriptively so every collaborator understands their purpose instantly.
  • Merge frequently to minimize divergence and reduce conflict complexity.
  • Clean up merged branches to keep your repository navigable.
  • Automate testing and deployment through CI/CD pipelines tied to your branching workflow.

Whether you're building a personal project or managing a team of engineers, the right hosting infrastructure makes a real difference. Fast NVMe storage accelerates Git operations, root access lets you configure your environment exactly as needed, and reliable uptime ensures your repositories are always accessible. Explore VPS Hosting plans designed for developers, or scale up to Dedicated Servers for high-demand team environments. If you're also managing web applications alongside your repositories, Shared Web Hosting offers a cost-effective option for smaller projects.

Your Git workflow is only as strong as the infrastructure supporting it — make sure both are built to last.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started