Skills101

Git & GitHub · Lesson 2 of 5 · Updated ·

Git Branching and Merging — Branches, Merge, Conflicts and Rebase

A branch is a separate line of work. You build a feature on its own branch while main stays stable; when it's ready, you merge it back.

main keeps going while a feature/login branch adds three commits; then the feature is merged back into main

1. Branch commands

git branch                       # list branches (* = current)
git switch -c feature/login      # create AND switch to a new branch
# ... edit, add, commit ...
git switch main                  # go back to main
git merge feature/login          # bring the feature into main
git branch -d feature/login      # delete the merged branch

(Older tutorials use git checkout -b — same idea.)

A branch is just a lightweight pointer to a commit, so creating one is instant.

2. Fast-forward vs merge commit

  • If main hasn't changed since you branched, Git just moves main forward — a fast-forward.
  • If both changed, Git creates a merge commit with two parents.

3. Merge conflicts

A conflict happens when both branches changed the same lines. Git can't guess which is right, so it asks you.

The conflicted file shows the HEAD version (price 499) and the incoming feature/pricing version (price 599) between conflict markers

How to resolve:

  1. git status lists the conflicted files.
  2. Open each file; find the <<<<<<<, =======, >>>>>>> markers.
  3. Edit to the correct final code (keep one side, the other, or combine) and delete the markers.
  4. git add file → git commit.

VS Code shows buttons: Accept Current, Accept Incoming, Accept Both.

Pull often and keep branches short-lived — small, frequent merges mean small, easy conflicts.

4. merge vs rebase

Merge keeps both lines of history plus a merge commit; rebase replays your commits on top of main for a straight line

git switch feature/login
git rebase main          # replay my commits on top of the latest main
mergerebase
Historytrue, with merge commitsclean, straight line
Rewrites commits?noyes (new ids)
Safe on shared branches?yesno

Golden rule: never rebase commits that others have already pulled. Rebase only your own local branch.

5. Branch naming

Teams usually use prefixes: feature/payment-upi, fix/login-crash, docs/readme, chore/upgrade-deps.

Common mistakes

  • Working directly on main for everything.
  • Leaving conflict markers in code and committing.
  • Rebasing a branch your teammates also use.

Quick recap

  • git switch -c name → work → git switch main → git merge name.
  • Fast-forward when main hasn't moved; otherwise a merge commit.
  • Conflicts: edit, remove markers, add, commit.
  • Merge = safe true history; rebase = clean line, only on your own branches.

Practice what you learned

📝 Quiz: Branching and Merging5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →