Git: branches, merge and rebase

Git records your project as a graph of commits. Branches are just labels pointing at commits, and merge and rebase are two ways to bring diverged work back together.

First commit

AHEAD → main
$ git init && git commit -m "A"

A commit is a snapshot of the project. "main" is a label pointing at the latest commit, and HEAD is the branch you are on.

Step 1 / 9
Bring the feature back withPlay both and compare the graphs.

Step by step

The example above, written out — the same steps the animation plays.

  1. 1First commit. A commit is a snapshot of the project. "main" is a label pointing at the latest commit, and HEAD is the branch you are on.
  2. 2Another commit. B points back to its parent A. The branch label moves forward to B.
  3. 3New branch. A branch is just a new label at the same commit — nothing is copied. HEAD now follows "feature".
  4. 4Work on the feature. Only "feature" moves. "main" still points at B.
  5. 5More feature work. C and D exist only on the feature branch.
  6. 6Back to main. Switching branches moves HEAD and swaps the files in your folder to that commit.
  7. 7Main moves on. Someone else's fix lands on main. The two branches have now diverged: both grew from B.
  8. 8Merge commit. Git creates a new commit M with two parents — E and D — combining both lines of work. Nothing is rewritten.
  9. 9History as it happened. The graph shows exactly when work branched and joined. Safe for shared branches; the cost is a busier history.

What's happening?

  1. Each commit points to its parent. Creating a branch only adds a label; HEAD tells Git which branch you are on.
  2. Merge joins two lines of work with a new commit that has two parents — history is kept as it happened.
  3. Rebase replays your commits on top of the other branch as new commits, giving a straight line of history — but rewriting what was there.

Where you'll meet it

Every pull request ends in a merge, a squash or a rebase. Knowing which keeps or rewrites history saves you from lost work and messy conflicts.

Common mistake

Rebasing a branch other people have already pulled. Their copies still have the old commits, and the histories no longer agree.

FAQ

Merge or rebase — which is better?

Merge keeps true history and is safe on shared branches; rebase gives a cleaner, linear history for your own unpushed work. Many teams rebase locally and merge pull requests.

What is a fast-forward?

When the branch you merge into has no new commits of its own, Git just moves its label forward — no merge commit needed.

Why do rebased commits get new ids?

A commit's id covers its parent too. Replaying a change on a new parent makes a new commit, even with identical changes.

What is HEAD?

A pointer to where you are — normally the branch you have checked out.