Track
Git Branch: A Guide to Creating, Managing, and Merging Branches
If you've ever worked on a group coding project, you know how quickly things can spiral out of control when multiple people try to update the duplicate files simultaneously. Conflicts arise, bugs sneak in, and progress grinds to a halt. That's where Git branches come in—not as an advanced trick but as the foundation of clean, parallel development.
In Git, branching isn't just encouraged; it's expected. Whether experimenting with a new feature, fixing a bug, or reviewing someone else's code, branches allow you to work without stepping on anyone else's toes. They allow you to break things, iterate, and then integrate your changes neatly into the main codebase.
This guide walks you through the essentials of branching in Git. We'll start with git branch
and git checkout
, then look more closely at how branches are created, managed, merged, and deleted. We'll also discuss best practices so you can keep your workflow conflict-free. I'm hoping that by the end of this guide, you will have a bigger understanding beyond memorizing commands: You will understand something more about the flow of work. If all this is interesting to you and you want to keep practicing, our Introduction to GitHub Concepts course is a great place to start.
Understanding Git Branches
Now that we've set the stage, let's break down what a Git branch is. At its core, a Git branch isn't a separate folder or a full copy of your codebase; it's just a lightweight pointer for a particular commit. This is one of the reasons Git stands out compared to older version control systems: branching is fast, cheap, and central to everyday workflows.
Think of a branch as a timeline. When you create a new branch, you essentially say, "Let's explore a new path from here." All your changes live on this path until you decide to merge them back into the main line or not. This flexibility makes it incredibly easy to try out ideas, build features in isolation, and collaborate with others without interfering with stable code.
Git keeps track of your current position in the project using a special reference called HEAD. When you switch branches, HEAD
points to the tip of the new branch. This behind-the-scenes detail allows Git to switch contexts so quickly, and it's also what makes commands like git checkout
and git switch
feel so seamless once you understand what’s happening under the hood.
By understanding how Git branches work, you'll unlock the power to organize your development workflow with clarity and confidence. If you're following along and want to test these concepts, DataCamp's Intermediate Git course walks through branching with plenty of guided practice.
Listing and Viewing Git Branches
So, you've created branches and started using them, but how do you keep track of everything? Fortunately, Git provides simple but powerful tools to list, sort, and filter branches so you never lose sight of your workflow.
Checking the current branch
To start, let’s check which branches exist in your local repository and identify which one you’re currently on.
git branch
This command lists all your local branches. You’ll notice an asterisk (*) next to your current branch. For an even more targeted look, try:
git branch --show-current
This returns just the name of the branch you're working in nice and clean.
Want to see remote branches too? Use:
git branch -r
And if you’d like to view both local and remote branches at the same time:
git branch -a
This gives you a complete picture of your project’s branching structure, which is especially helpful when collaborating with others on platforms like GitHub.
Sorting and filtering branches
As your project grows, so will your list of branches. Sorting and filtering help you manage this list effectively. To sort branches by the latest commit date, use:
git branch --sort=-committerdate
You can also sort by other criteria, such as author name, creation date, or upstream configuration. Here’s a handy one for filtering branches that contain a specific commit:
git branch --contains <commit>
This shows you which branches have already included a given commit, which helps check if a bug fix or feature has been merged into them. Conversely, the command below shows you which branches haven’t picked up that commit yet:
git branch --no-contains <commit>
Managing branches effectively involves creating them, as well as ensuring visibility and control. These commands help keep your development clean, organized, and efficient.
Want to master how these relate to collaboration? The Foundations of Git course provides an excellent base and covers real-world workflows you'll use repeatedly.
Creating a New Git Branch
Now that you understand how to list and switch between branches, let’s walk through creating them. Branching is a core part of Git’s workflow, and fortunately, creating new branches is straightforward, whether you're setting up a feature branch, hotfix, or experimenting with something entirely new.
Creating a branch without switching
Sometimes, you want to create a branch without immediately moving into it. This is useful when you’re preparing multiple branches at once or when setting up workflows for others.
git branch new-feature
This command creates a branch named new-feature
, but you’ll still be on your current branch. You can switch to it later when you're ready to work on it.
Creating and switching to a branch simultaneously
If you're jumping straight into development, you can create and switch to the new branch in one move. In older Git versions, you’d use:
git checkout -b new-feature
However, in modern Git, the more transparent and more intuitive approach is:
git switch -c new-feature
This not only creates the branch but also checks it out immediately, so you're ready to start working.
Setting upstream branches
When you're working with remote repositories, you’ll often want your local branch to track a remote one. This makes pushing and pulling updates simpler. To create a branch that tracks a remote branch right from the start, use:
git branch --track new-feature origin/new-feature
If you’ve already created the branch and want to set or change the upstream, this command does the trick:
git branch --set-upstream-to=origin/new-feature
This configuration ensures your local branch knows which remote branch to pull from or push to, keeping your workflow smooth and connected.
Switching Between Git Branches
Once you've created a few branches, you'll often need to hop between them, whether you're jumping back to the main
to merge a fix or switching to a feature branch to continue coding. Git makes this process seamless, and, like most things related to Git, there is more than one way to do it.
Using git checkout
For a long time, git checkout
was the go-to command for switching branches:
git checkout feature-login
This command switches your working directory to the feature-login
branch, updating all your files to reflect the snapshot of that branch. It’s reliable and still widely used. But here’s the thing: git checkout
does a lot of things. It's used to switch branches, restore files, and even check out commits. That can get confusing, especially if you're starting.
Using git switch
To make things more intuitive, Git introduced the git switch
in version 2.23:
git switch feature-login
This does exactly what you expect: switches branches. It doesn't touch your working tree or reset your files unless you tell it to. It's simpler, safer, and easier to teach and remember.
So, when should you use which?
- Use
git switch
for switching between branches—it's clear and purpose-built. - Use
git checkout
if you need to restore files or check out a specific commit.
Merging Git Branches
So, you've been working on a feature in a separate branch. Now comes the moment of truth: combining your changes into the main branch. In Git, this process is called merging. Depending on the history of your branches, there are several ways to approach it.
Fast-forward merge
Let’s say your feature branch
started from the main
, and while you were working on it, nobody else touched the main
. In this case, Git doesn’t need to do much thinking. It simply moves the main
pointer forward to the latest commit in feature-branch
.
git checkout main
git merge feature-branch
No new commit is created—Git fast-forwards main
. Clean, simple, and perfect for solo projects or short-lived branches.
Three-way merge
Things get more interesting when both branches have progressed independently of each other. Your teammate may have added some changes to the main while you were coding in the feature branch
. Now, Git has to look at three snapshots: the common ancestor, your branch, and the target branch.
git checkout main
git merge feature-branch
In this case, Git creates a new merge commit to combine the two branches. If there are conflicts, say you and your teammate changed the same line in the same file, and Git will prompt you to resolve them manually. You'll edit the file, mark it as resolved, and then commit the merge.
git add .
git commit
If this sounds a little intimidating, our Git Merge Tutorial: A Comprehensive Guide with Examples is an excellent walkthrough that covers all the essentials, including handling conflicts gracefully.
Rebasing instead of merging
Are you not a fan of merge commits cluttering your history? You're not alone. That's where Git rebase
comes in. Instead of creating a new merge commit, rebase
replays your changes on top of another branch, resulting in a cleaner, linear history.
git checkout feature-branch
git rebase main
Then, when you merge, Git sees a straight line—there is no need for a merge commit. However, use it with caution, especially when working with shared branches. Rewriting history can be dangerous if others are working on the same code.
To learn when it’s best to use merge vs. rebase (and how to rebase safely), the Intermediate Git course offers practical, hands-on guidance.
Deleting Git Branches
After a successful merge, it’s a good idea to clean up any branches you no longer need both locally and remotely. It keeps your workspace tidy and your Git history easier to navigate. Let’s walk through how to do that without losing sleep over accidentally deleting something important.
Deleting local branches
When a branch has been merged and its job is done, you can safely delete it from your local repository:
git branch -d feature-branch
The -d flag stands for “delete.” Git will check to ensure the branch has already been merged to avoid potential data loss.
But what if you want to delete a branch, even if it's merged? That's where the capital -D comes in:
git branch -D feature-branch
This forces deletion, even if Git warns you the branch hasn't been merged. Before hitting enter, just be sure you don't need those changes.
Looking for a deeper dive into managing your local workspace and branches? Check out our Git Pull Force: How to Overwrite a Local Branch With Remote tutorial. It's a helpful companion to ensure you're not just deleting but managing branches safely.
Deleting remote branches
Local cleanup is only half the job. If the branch also lives on a remote (like GitHub), you'll want to remove it there, too, especially if you're done with the feature or bug fix.
git push origin --delete feature-branch
This command tells Git to remove the branch from the origin remote. It's clean and direct, helping to prevent your remote from becoming cluttered with unused branches.
Once you've deleted remote branches, cleaning up your local tracking references is also a good idea.
git fetch -p
The -
p
stands for "prune." It removes any stale remote-tracking branches that no longer exist on the server.
For more helpful Git hygiene habits, the Git Push and Pull Tutorial and Complete Git Cheat Sheet are perfect quick references.
Pushing and Pulling Git Branches
Once you've created and organized your branches locally, the next step is to sync them with the remote repository. This is essential for collaboration and backup. Let's walk through how to push, pull, and track branches effectively.
Pushing a new branch to remote
You've created a new feature locally and tested it, and now you want to share it with your team or back it up. To push a new branch to a remote repository (typically named origin
), use:
git push -u origin new-feature
The -u
flag (short for --set-upstream
) tells Git to remember the remote branch for future pulls and pushes. That way, next time, you can just run git pull
or git push
without specifying the branch.
If you’re wondering what else happens behind the scenes during a push or pull, our Git Push and Pull Tutorial explains it with examples you can follow.
Pulling changes from a remote branch
Let’s say someone else pushed updates to the same branch you’re working on. You’ll want to pull those changes down to stay in sync:
Git pull origin new-feature
This fetches the latest commits from the remote and merges them into your local branch. If you want to avoid merging commits, consider using the following:
git pull --rebase origin new-feature
As the merging section explains, --rebase
helps keep your commit history clean.
Tracking a remote branch
When you want to start working with a branch that already exists on the remote, the easiest way to set things up is:
git checkout --track origin/feature-xyz
This command checks out the remote branch and automatically sets up tracking, so future pulls and pushes are a breeze.
Common Issues and Troubleshooting
Even with the best workflows, things don’t always go smoothly. Whether it’s a merge conflict, an accidentally deleted branch, or some uncommitted changes getting in your way, Git has tools to help you recover. Let’s look at some of the most common branching issues and how to fix them.
Handling merge conflicts
You've just tried merging a branch, and Git throws a merge conflict. This happens when two branches change the same part of a file differently, and Git can't decide which change to keep.
Here’s how to tackle it:
git status
This tells you which files conflict. Then, you can use:
git diff
To see what's causing the issue. From there, manually open the conflicting file(s), resolve the differences, and then
git add <resolved-file>
git commit
If you'd like to learn more about merging workflows and resolving conflicts, check out the Git Merge Tutorial, which provides a complete walkthrough.
Recovering deleted branches
Accidentally deleted a branch, and feeling the panic set in? Don’t worry—it’s not lost forever if you act fast.
You can recover it using git reflog
, which logs your recent HEAD positions:
git reflog
Find the commit hash from before you deleted the branch, then recreate it with:
git checkout -b your-branch-name <commit-hash>
And just like that, your branch is back. Want to understand better how Git tracks these references? Our Git Reflog Guide explains it with real examples.
Stashing changes before switching
Sometimes, you want to switch branches, but you have uncommitted changes. Git won't let you switch if it might result in lost work. That's where git stash
comes in.
git stash
And Git will temporarily set your changes aside. After switching branches, you can bring them back with:
git stash pop
This is especially helpful when jumping between features or hotfixes.
If you’re managing a lot of changes or cleaning up your working directory, you might also be interested in Git Clean: Remove Untracked Files and Keep Repos Tidy.
Advanced Branching Strategies
By now, you've seen how to create, switch, and manage Git branches with ease. But how do teams use these branches in real-world projects? The answer lies in choosing the right branching strategy—a structure for how and when to use branches in your development workflow. Let's explore some of the most popular approaches.
Feature branch workflow
The feature branch workflow is one of the most common strategies, especially in collaborative projects. Here’s how it works:
Each new feature gets its own branch, created from the main (or develop) branch. This allows developers to work independently without affecting production-ready code.
git switch -c feature/login-page
Once the feature is complete and tested, it’s merged back into the main branch (or a staging branch) via a pull request.
This model helps isolate work, makes code reviews more manageable, and avoids cluttering your main branch with half-finished features. To keep remote collaboration smooth, don’t forget to push your branches:
git push -u origin feature/login-page
Do you need a refresher on pushing and pulling branches? The Git Push and Pull Tutorial walks you through the entire process.
GitFlow workflow
If you’re working on a project with regular releases, GitFlow might be a good fit. This workflow introduces structured roles for different branch types:
-
main
: always contains production-ready code. -
develop
: integration branch for features. -
feature/*
: short-lived branches for new features. -
release/*
: pre-production branches for testing. -
hotfix/*
: Quick fixes are based on themain
.
Here’s a quick example of starting a new feature branch using GitFlow tools:
git flow feature start payment integration
This strategy adds a bit of complexity, but it shines in larger teams where clear structure and stability are priorities. If you’re exploring workflows beyond GitHub, check out What GitLab Is: Features, Benefits, and How to Get Started for another take on structured Git practices.
Trunk-based development
Do you prefer minimal branching and rapid delivery? Trunk-based development might be your style. In this strategy, all developers commit to a single branch, usually the main
, with small and frequent commits. Instead of long-lived feature branches, this approach encourages short-lived branches or direct commits to the main
branch.
It's fast and straightforward but requires discipline, strong test automation, and good communication. This model is standard in startups and teams practicing DevOps or CI/CD. Choosing a branching strategy depends on your team's size and release cadence, and also, of course, the level of collaboration.
Conclusion
Branches are at the heart of Git's version control system. They allow developers to work on new features, bug fixes, and experiments in isolation without disrupting the main codebase. This flexibility leads to cleaner, more organized workflows and better team collaboration.
By committing frequently, merging responsibly, and maintaining a clean branch structure, you reduce the risk of conflicts and make your codebase more straightforward to navigate and maintain. Without a doubt, mastering Git branches helps you deliver better software over time.
Tech writer specializing in AI, ML, and data science, making complex ideas clear and accessible.
Learn Git Fundamentals Today
Learn Git with DataCamp
Track
Git Fundamentals
Course
Introduction to Git
Tutorial
GitFlow Tutorial: Branching for Features, Releases, and Hotfixes

Patrick Brus
15 min
Tutorial
Git Merge Tutorial: A Comprehensive Guide with Examples

Srujana Maddula
15 min
Tutorial
Git Commit Tutorial: How to Track and Document Code Changes
Tutorial
Git Switch Branch: A Guide With Practical Examples

François Aubry
8 min
Tutorial
Git Tag Tutorial: How to Create, Manage and Use Tags

Patrick Brus
8 min
Tutorial