Merging Branches in Git – How to Combine Code Safely

Why Merge Branches?

When working in Git, developers create branches to work on features or fixes independently. Once the work is complete, merging integrates the changes into the main branch (e.g., main or develop).

Merging allows:

Feature Integration – Combine new features into the main project.
Bug Fixes – Apply fixes without disrupting other development work.
Collaboration – Keep work synchronized across teams.

This guide explains how to merge branches, handle conflicts, and choose the right merge strategy.


Preparing for a Merge

Before merging, ensure your branch is up to date:

git checkout main

or using the newer command:

git switch main

Then, pull the latest changes from the remote repository:

git pull origin main

This prevents potential conflicts by ensuring your branch has the latest updates.


Merging Branches in Git

Fast-Forward Merge (Default Method)

A fast-forward merge happens when there are no new commits in the target branch (main). Git simply moves the branch pointer forward.

git merge feature-branch

✅ Used when main hasn’t changed since the branch was created.
✅ Keeps a linear commit history.

If you prefer to keep a record of the merge, use:

git merge --no-ff feature-branch

This ensures a merge commit is created.


3-Way Merge (Standard Merge)

A 3-way merge is required when both branches have new commits. Git combines the changes and creates a new merge commit.

git checkout main
git merge feature-branch

or

git switch main
git merge feature-branch

✅ Used when main and feature-branch both have new commits.
✅ Keeps a detailed history of merged branches.


⚠ Handling Merge Conflicts

If Git cannot automatically merge the branches, it will show a merge conflict message.

Steps to Resolve Merge Conflicts

1️⃣ Check which files have conflicts:

git status

2️⃣ Open the conflicting files. Git marks conflicts like this:

<<<<<<< HEAD
Current changes in main branch.
=======
Changes from feature-branch.
>>>>>>> feature-branch

3️⃣ Manually edit the file to keep the correct changes.
4️⃣ Stage the resolved file:

git add <file-name>

5️⃣ Complete the merge:

git commit -m "Resolved merge conflict in <file-name>"

Merging Remote Branches

If merging a remote branch, first fetch the latest changes:

git fetch origin

Then merge:

git merge origin/feature-branch

️ Aborting a Merge

If something goes wrong during a merge, cancel it:

git merge --abort

This restores the branch to its previous state.


Next Steps

Now that you know how to merge branches, explore more Git topics:

Handling Merge Conflicts – Learn how to resolve merge conflicts efficiently.
Collaborating with GitHub – Work with pull requests and code reviews.
Collaborating with GitLab – Manage merge requests and workflows.

Need help? Check the official Git documentation or ask in the comments!