Merging Branches

git merge brings the commits from one branch into another.

Syntaxgit switch main git merge <feature-branch>

When a feature is ready, you merge it back into main. Switch to the branch that should receive the changes, then merge the other branch into it.

Fast-forward vs merge commit

  • Fast-forward — if main has no new commits, Git just moves the pointer forward. No extra commit is created.
  • Merge commit — if both branches advanced, Git creates a new commit that ties the two histories together.
A feature branch diverging from main and being merged back with a merge commitmainmergefeature branch
The blue commit ties the feature branch back into main.

Example

Example · bash
# Move to the branch that receives the work
git switch main

# Merge the feature branch into main
git merge login-page

# Ask Git for a merge commit even if fast-forward is possible
git merge --no-ff login-page

When to use it

  • A developer merges a completed feature branch into main after the pull request is approved, integrating the new code.
  • A release manager merges hotfix/crash-fix into both main and release/1.4 to keep all supported versions patched.
  • A team uses squash merges to collapse a noisy feature branch into a single clean commit on main.

More examples

Fast-forward merge a feature branch

When main has no new commits since the branch was created, Git simply moves the pointer forward with no merge commit.

Example · bash
git switch main
git merge feature/user-auth
# Fast-forward
# src/auth.py | 42 +++++++++

Create a merge commit explicitly

--no-ff forces a merge commit even when a fast-forward is possible, preserving the branch topology in history.

Example · bash
git switch main
git merge --no-ff feature/payments
# Opens editor for merge commit message
# Merge made by the 'ort' strategy.

Squash merge for a clean history

Squash combines all branch commits into a single staged diff; you then write one clean commit message before it lands on main.

Example · bash
git switch main
git merge --squash feature/search
git commit -m "feat: add full-text search (#42)"

Discussion

  • Be the first to comment on this lesson.