Branching & Merging

💤0
Lv 10 XP
← 🧱 Foundations · Git & GitHub

Branching & Merging

Intermediate ⭐ 80 XP ⏱ 20 min #git#branching#merge

Work on features in isolation with branches, then integrate them with merges.

📖Theory

A branch is just a movable pointer to a commit. Creating one is cheap, so the standard workflow is: branch off main, build a feature in isolation, then merge it back. This keeps main stable and lets several efforts proceed in parallel.

Merging combines histories. A fast-forward merge simply moves the pointer forward when there’s no divergence. A three-way merge creates a new merge commit when both branches have new work. A conflict happens when the same lines changed on both sides — Git pauses and asks you to decide.

gitGraph
  commit
  branch feature
  checkout feature
  commit
  commit
  checkout main
  merge feature
A feature branch merged back into main
🌍Real-World Example
git switch -c feature/login     # create + switch to a branch
# ...make commits...
git switch main                 # back to main
git merge feature/login         # integrate the feature
git branch -d feature/login     # delete the merged branch

# On a conflict:
git status                      # see conflicted files
# edit files, remove <<<< ==== >>>> markers
git add <file> && git commit    # finish the merge
✍️Hands-On Exercise
  1. Create a branch, make two commits, and merge it back into main.
  2. Deliberately cause a conflict by editing the same line on two branches; resolve it.
  3. Use git log --oneline --graph --all to visualize your branch structure.
  4. Explain when Git can fast-forward instead of creating a merge commit.
🧾Cheat Sheet
TaskCommand
New branchgit switch -c name
Switchgit switch name
List branchesgit branch
Merge into currentgit merge name
Delete mergedgit branch -d name
Visualizegit log --graph --oneline --all
Abort a mergegit merge --abort
💬Common Interview Questions
What is a fast-forward merge?

When the target branch has no new commits of its own, Git just moves its pointer forward to the feature branch’s tip — no merge commit is needed.

Why use feature branches?

They isolate work in progress so main stays releasable, enable parallel development, and give a natural unit for code review via pull requests.

How do you resolve a merge conflict?

Edit the marked regions to the desired result, remove the conflict markers, git add the files, and commit to complete the merge.

📚Official Documentation

📝 My notes on this topic

Auto-saves as you type