Git fundamentals: commits, history, and branches · Lesson 4 of 5

Lesson 4: Work on a branch without fear

Lesson objectives:

  • Explain what a branch is.
  • Create a branch with git branch and switch to it with git 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

  1. git branch experiment creates a new branch called experiment.
  2. git switch experiment moves you onto that branch.
  3. You edit and commit as normal.
  4. git switch main takes you back to the main branch.
  5. git merge experiment brings the changes from experiment into main.

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

  1. Pro Git, Basic Branching and Merging — https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

Exercises

01

In git-practice, create a branch called idea, add a file, commit it, switch back to main, and check whether the file exists.

Level 1 (warm-up)
Done criteria · checked locally
02

Merge your idea branch back into main and then delete the idea branch.

Level 2 (advanced)
Done criteria · checked locally