Git & GitHub Course
Git & GitHub
/
Intermediate

git merge

Definition

A command that joins two or more development histories together. It takes the contents of a source branch and integrates them into a target branch.

Explain Like I'm New

You finished building 'Dark Mode' on your experimental branch. Now you want to put that code into the official `main` codebase. You go to `main`, and 'merge' the dark mode branch into it.

Real World Example

Shipping a feature. Once the code is reviewed, it is merged into the master branch so it can be deployed to users.

Common Use Cases

  • •Integrating feature branches
  • •Receiving updates from teammates

Merge vs Rebase

Featuregit mergegit rebase
HistoryPreserves absolute history. Creates a new 'Merge Commit' tying the two branches together.Rewrites history. Moves your entire branch to the very tip of the main branch, creating a perfectly straight line.
TraceabilityExcellent. You can see exactly when the branches diverged and came back together.Poor. It lies about history, making it look like you wrote your code after the main branch finished, even if you didn't.
Conflict ResolutionYou resolve all merge conflicts at once in a single massive merge commit.You resolve conflicts one-by-one for every single commit you are rebasing.
Safety Rule100% safe to use on public branches shared with other developers.DANGER: Never rebase a public branch. It rewrites history and will break your coworkers' local repositories.

Terminal Output

bash / terminal
# Scenario: You finished 'feature-login' and want to merge it into 'main' # Step 1: Switch to the receiving branch (main) $ git checkout main # Step 2: Merge the feature branch INTO main $ git merge feature-login # Step 3 (Optional): Delete the feature branch now that it is merged $ git branch -d feature-login

Interview Questions

basic

  • Before running `git merge feature-branch`, which branch must you be currently checked out on?

intermediate

  • What is a 'Fast-Forward' merge?

Flash Cards

Question

Which branch to be on?

Click to reveal answer
Answer

You must be on the RECEIVING branch. If you want `main` to receive the feature, you must `git checkout main` first, and then run `git merge feature-branch`.

Question

Fast-Forward?

Click to reveal answer
Answer

If the `main` branch hasn't changed at all since you created your feature branch, Git doesn't need to do any complex math. It just instantly moves the `main` pointer forward to match your feature branch. No extra 'Merge Commit' is required.