Lesson 4: Work on a branch without fear
Lesson objectives:
- Explain what a branch is.
- Create a branch with
git branchand switch to it withgit switch.- Merge a branch back into the main branch.
Prerequisites: Lessons 01-03 (commits,
git log,git restore) | Previous << 03 | Next 05 >>
Two ideas at once
Imagine you are writing a blog post. You want to try a new opening paragraph, but you do not want to risk messing up the draft that already works. You could copy the whole folder, but then you have two versions to keep in sync.
A branch is a separate line of development inside the same repository. You can create a branch, make commits on it, and decide later whether to keep it 1. The main branch is usually called main or master.
HEAD is a pointer to the commit you are currently looking at. When you switch branches, HEAD moves to the latest commit on that branch.
How branching works
git branch experimentcreates a new branch calledexperiment.git switch experimentmoves you onto that branch.- You edit and commit as normal.
git switch maintakes you back to the main branch.git merge experimentbrings the changes fromexperimentintomain.
The diagram shows a branch splitting from the main line and moving forward on its own.
Worked example (follow along)
Stay in git-practice.
After the merge, draft.txt on main includes the experimental line.
Your turn (faded example)
Fill in the missing commands to create a branch, switch to it, and merge it back.
Answer:
Summary + what's next
You can now create a branch, switch to it, and merge it back. This is the last of the four core skills. In the next lesson, you will combine init, commit, branch, and recovery into one small real-world workflow.
Footnotes
-
Pro Git, Basic Branching and Merging — https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging ↩