← Back to Git Course | Chapter 3: Branching | Lesson 5 of 9

Git merge Command

A merge is like combining two versions of a group story into one. When nobody else changed the main story, Git simply moves it forward without any extra fuss.
Syntax
bash
git checkout target_branch
git merge source_branch
git merge --squash source_branch

Fast-Forward Merges

A fast-forward merge happens when the target branch hasn't moved since your feature branch split off from it -- Git doesn't need a merge commit at all, it just slides the branch pointer forward to include the new commits.

Example: Fast-Forward Merges

bash
git checkout main
git merge feature-x

Three-Way Merges

When both branches have gained their own separate commits since diverging, Git can't just fast-forward -- it performs a three-way merge, combining both histories and creating a new merge commit with two parents.

Example: Three-Way Merges

bash
git checkout main
git merge feature-y

Squash Merges

A squash merge (git merge --squash) takes every commit from the source branch and flattens them into a single new commit on the target branch, trading detailed history for a cleaner, simpler main-branch log.

Example: Squash Merges

bash
git checkout main
git merge --squash feature-z
git commit -m "Add feature z"

Handling Merge Conflicts

When the same lines of the same file were changed differently on both branches, Git can't automatically decide which version to keep -- it pauses the merge and marks the conflicting sections in the file for you to resolve by hand.

Example: Handling Merge Conflicts

bash
git merge feature-x
# CONFLICT (content): Merge conflict in file.txt
git add file.txt
git commit

Verifying Merged Branches

git branch --merged lists branches whose commits are already fully included in your current branch, and --no-merged shows the opposite -- both are useful for finding stale feature branches that are safe to delete.

Example: Verifying Merged Branches

bash
git branch --merged
git branch --no-merged
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Merging while on the wrong branch, such as running git merge main on main, when you must switch to the branch that should receive the changes.
  2. Continuing after a conflict without resolving the <<<<<<< markers, and committing them into the file.
  3. Using git merge --squash and expecting the source branch's history to appear, when it produces one combined change that you must commit yourself.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.