Branching and Merging
A branch is a lightweight, movable pointer to a commit. Branching lets you work on a change in isolation, and merging brings it back together with the work of others.
Core commands
git switch -c feature/login # create a branch and switch to it
git switch main # switch back to main
git branch # list local branches (-a includes remote ones)
git merge feature/login # merge that branch into the branch you are on
git branch -d feature/login # delete a branch that has been merged
git switch is the modern command. Older documentation uses git checkout for the same job, and it still works.
What a merge does
- If
mainhas not moved since you branched, Git just moves the pointer forward (a fast-forward). No new commit is created. - If both branches have new commits, Git creates a merge commit that combines them. If the changes overlap, you get a merge conflict.
Rebase in one paragraph
git rebase main replays your commits on top of the latest main, which gives a straight, linear history. It rewrites your commits, so only rebase commits that nobody else has pulled.
Working practice
- Branch from an up-to-date
main. - Keep branches short-lived and focused on one change.
- Bring in changes from
mainregularly, so differences stay small. - Delete the branch after it has been merged.
- Follow your team’s naming convention (for example
feature/...andfix/...).
Try it
Create a branch, commit a change, switch back to main and notice that the change is gone. Merge the branch and watch it return.
Common mistakes
- Branching from an out-of-date main.
- Letting a branch live for weeks, so the merge becomes painful.
- Rebasing commits that are already pushed and shared.
Check yourself
- When does a merge create no merge commit?
- Why is rebasing shared commits a problem?