How to Merge One Branch into Another in Git

When working with Git, one of the most common tasks you’ll perform is merging—bringing the changes from one branch into another. Whether you’re finishing a feature or integrating bug fixes, merging helps you combine the work of multiple contributors or development lines.

In this post, you’ll learn how to safely and effectively merge one branch into another using Git.


🧠 What Is a Git Merge?

Merging in Git means combining the changes from one branch into another. The most common use case is merging a feature branch into the main (or master) branch.


🔀 Basic Syntax

git checkout target-branch
git merge source-branch
  • target-branch: The branch you want to merge changes into.
  • source-branch: The branch with changes you want to bring from.

🛠️ Step-by-Step: Merge a Branch

Example: Merge feature/login into main

1. Switch to the target branch

git checkout main

2. Pull the latest changes (optional but recommended)

git pull origin main

3. Merge the source branch

git merge feature/login

4. Push the merged result to the remote

git push origin main

✅ What Happens During a Merge?

  • Git tries to automatically merge changes.
  • If there are no conflicting changes, it creates a merge commit.
  • If there are conflicts, you’ll need to resolve them manually.

⚔️ Resolving Merge Conflicts

If Git reports a conflict:

  1. Open the conflicted files (they’ll be marked in your Git status).
  2. Look for conflict markers like:
<<<<<<< HEAD
your code
=======
incoming code
>>>>>>> feature/login
  1. Edit and resolve the differences.
  2. Mark the conflict as resolved:
git add <filename>
  1. Complete the merge:
git commit

🔄 Optional: Merge Without a Commit (Fast-forward)

If the target branch is behind the source and no diverging changes exist, Git will do a fast-forward merge, updating the target branch pointer directly.

Use:

git merge --ff-only feature/login

🧪 Bonus: Prevent Conflicts with Rebase (Optional Strategy)

Before merging, you can rebase your source branch on the latest target branch to reduce conflicts:

git checkout feature/login
git rebase main

Then switch back to main and merge.


🔁 Summary of Merge Commands

TaskCommand
Switch to target branchgit checkout main
Merge another branch into itgit merge feature-branch
Push merged changesgit push origin main
Resolve conflictsManually fix, then git add + commit
Rebase before merging (optional)git rebase target-branch

🧩 Final Thoughts

Merging is a core part of collaborative Git workflows. With a clear understanding of how to merge branches—and resolve any conflicts—you’ll be better equipped to manage projects and keep your version history clean.

Sharing Is Caring:

Leave a Comment