← Back to all tutorials

Merging Branches

Learn about Merging Branches

Merging is how you combine work from one branch into another. After building a feature on a separate branch, you merge it back into main to make it part of the production code. This is one of the most important Git operations you'll use in a team workflow.

Basic Merge

# Step 1: Switch to the branch you want to merge INTO
git switch main

# Step 2: Merge the feature branch
git merge feature/login

Types of Merges

Fast-Forward Merge

If main has no new commits since the feature branch was created, Git simply moves the main pointer forward. No merge commit is created:

# Before:
# main:           A - B - C
#                          \
# feature/login:            D - E

# After git merge:
# main:           A - B - C - D - E    (pointer moved forward)

# Force a merge commit even in fast-forward situations:
git merge --no-ff feature/login

Three-Way Merge

If both branches have new commits since they diverged, Git creates a merge commit that combines both:

# Before:
# main:           A - B - C - F - G
#                          \
# feature/login:            D - E

# After git merge:
# main:           A - B - C - F - G - M (merge commit)
#                          \           /
# feature/login:            D - E ----

Squash Merge

Combine all branch commits into a single commit on the target branch. Creates a cleaner history:

git merge --squash feature/login
git commit -m "Add login feature"

# All changes from feature/login appear as one commit

Merge Conflicts

When both branches modify the same lines in the same file, Git can't automatically merge and marks it as a conflict:

git merge feature/login
# Auto-merging src/app.js
# CONFLICT (content): Merge conflict in src/app.js
# Automatic merge failed; fix conflicts and then commit the result.

The conflicted file will contain conflict markers showing both versions. You need to choose which version to keep, remove the markers, then stage and commit.

Resolving Conflicts

  1. Open the conflicted file
  2. Choose which version to keep (or combine both)
  3. Remove the conflict markers
  4. Stage and commit
# After fixing the file:
git add src/app.js
git commit -m "Merge feature/login, resolve greeting conflict"

Aborting a Merge

# If conflicts are too messy, bail out
git merge --abort
# Everything goes back to before the merge

Merge Strategies for Teams

# 1. Always merge with a merge commit (recommended for teams)
git merge --no-ff feature/login -m "Merge feature/login into main"

# 2. Squash merge (clean single-commit history)
git merge --squash feature/login
git commit -m "feat: add login feature"

# 3. Rebase then fast-forward (linear history)
git switch feature/login
git rebase main
git switch main
git merge feature/login

What's Next

You can now merge branches and handle conflicts. In the final episode, we'll learn about deleting branches and keeping your repository clean after merges.