3.3 Branching and Merging
Prerequisites: Staging Area, Differences, and Safe Undo Estimated time: 12 minutes Practice environment: Continue using the temporary repository cleaned up from the previous page You are ready to continue when: you can draw branch pointers and distinguish fast-forward merges from three-way merges
After the undo exercise, a new task says, "Try the change without affecting the main line." Git does not copy the entire project for this; a branch is a reference that moves with each commit.
Create a Topic Branch
git switch -c experiment
printf '%s\n' "print('from experiment')" >> main.py
git add main.py
git commit -m 'Add experimental output'
git branch --show-current
git log --graph --oneline --decorate --allAt this point, you can think of the commit graph as:
main A
\
experiment B <- HEADHEAD typically points to the current branch, experiment points to the new commit B, and main still points to A. Switching branches causes the work area to match the target commit; if the switch would overwrite uncommitted changes, Git usually refuses it. In this case, you should commit, stash, move, or explicitly discard your changes, never force a bypass of these checks.
Fast-Forward Merge
git diff main...experiment
git switch main
git merge --ff-only experiment
git branch -d experimentMoving main directly from A to B is a fast-forward. --ff-only refuses a merge when the commit graph has diverged, making it useful when only a linear advance is allowed.
Deleting experiment does not remove B, because main can still reach it. Unmerged branches using git branch -d are rejected; -D forcibly removes the reference. Use with caution, ensure the commit can still be recovered or confirm that it is truly no longer needed before performing this operation.
Three-Way Merge
If main and the topic branch have both made commits since sharing a common ancestor, a standard git merge topic compares the common ancestor with the state of both branches. When there are no content conflicts, Git typically creates a merge commit:
B---C topic
/ \
A---D-------M mainWhether to keep the merge commit, squash it, or require a linear history is a team policy. Before actually merging, first use git status --short to verify the working directory, then use git log --graph --oneline --decorate --all to inspect the commit graph, and finally review the net changes being merged with git diff main...topic-branch.
A...B typically compares the changes from the common ancestor to point B in the diff; in the log, the three-point syntax has a different meaning, so avoid mixing up explanations when consulting the command manual.