Git & GitHub ยท Chapter 16 of 42

git merge

Merging combines the changes from one branch into another. Typically, you merge a feature branch back into `main` once the feature is complete and tested.

Git performs a 'fast-forward' merge when possible (simply moving the branch pointer forward), or creates a merge commit when both branches have diverged with separate new commits.

Syntax
git switch main
git merge feature-branch

Performing a merge

Switch to the branch you want to merge into (usually main), then run `git merge branch-name` to bring in the other branch's changes.

Fast-forward vs merge commit

If main hasn't changed since the feature branch was created, Git does a fast-forward merge. If both branches have new commits, Git creates a merge commit joining both histories.

Example 1 (bash)
git switch main
git merge feature-login
Output
Updating a3f5c9e..9c2e1aa
Fast-forward
 app.js | 10 +++++-----

Merges feature-login into main using a fast-forward merge since main had no new commits.

Example 2 (bash)
git merge feature-payments
Output
Merge made by the 'ort' strategy.
 payments.js | 20 ++++++++++++++++++++

Creates a merge commit because both branches had diverged with separate commits.

Key points

  • git merge combines changes from one branch into another.
  • A fast-forward merge simply moves the branch pointer.
  • A merge commit is created when branches have diverged.
  • Always merge into the target branch after switching to it.
๐Ÿ’ก Note: It's good practice to pull the latest changes on main before merging your feature branch into it.

๐Ÿ“ Quick Quiz

1. What does git merge do?

2. When does Git perform a fast-forward merge?

3. What is created when merging two diverged branches?