Skip to main content

Getting Started with Git · Chapter 4 / 5

Organize your work with branches

A branch lets you work on an idea without breaking what already works. You'll learn to create branches, switch between them and merge them.

Chapter 4 / 5

Step 01 / 15

In this chapter

So far, all your commits have followed one another in a single line. Branches let you open separate lines of work, then bring them back together.

By the end of this chapter, you will be able to:

  • Explain what a branch is and what it's used for
  • List, create and switch branches
  • Rename and delete a branch
  • Merge one branch into another with git merge
  • Read the branch graph with git log --graph

Step 02 / 15

What is a branch?

Concept

Branch: an independent line of work. In practice, it's just a label attached to a commit.

When you create a repository, Git creates an initial branch: main. Every commit you make is added to the end of this branch, and the main label moves forward with it.

Creating a new branch just means adding a second label. Commits you make on that branch don't show up on main until you bring the two together.

A
B
feature
HEAD
C
main

HEAD marks the active branch

Each branch is just a label placed on a commit. HEAD follows the branch you’re on.

The analogy

In the photographer's notebook, a branch is a bookmark. You can add several bookmarks and pick up the story from any of them. Adding a bookmark doesn't copy the notebook.

Tip

A branch is not a copy of your project. Creating a branch is instant and takes almost no space, even on a very large project.

“Creating a branch copies all of the project's code.” True or false?

Step 03 / 15

Why work with branches?

Without branches, everyone works on main. If you commit a half-finished feature, main no longer works. And if an urgent bug comes up, your work in progress is in the way.

With branches, main always stays stable. Each topic gets its own branch:

  • A new feature: feature/contact-form
  • A bug fix: fix/mobile-menu
  • An experiment you're not sure you'll keep: test/new-font
ABCDEMfeaturemainHEADmerge commit
Each commit points to its parent. Branches split off and merges bring them back together: that’s the commit graph (DAG).

When the work is ready, you merge it into main. If the experiment doesn't work out, you delete the branch: main was never touched.

The analogy

It's like writing a rough draft. You try things, cross them out, start over. When it's right, you write out a clean copy.

Step 04 / 15

See your branches: git branch

git branch on its own lists your local branches:

$ git branch

  feature/contact-form
* main

The star * marks the branch you're on. Here, main.

To see the remote repository's branches too, add -a (all):

$ git branch -a

  feature/contact-form
* main
  remotes/origin/main

Branches starting with remotes/origin/ are your local copies of the branches on GitHub. They're updated when you run git pull.

In the list shown by git branch, what does the star * mean?

Step 05 / 15

Create a branch

$ git branch <branch-name>

$ git branch fix/mobile-menu

The branch is created from the commit you're on. Watch out: git branch creates the branch, but you stay on your current branch. The star hasn't moved:

$ git branch

  feature/contact-form
  fix/mobile-menu
* main

Practice

Before creating a branch, use git status to check that you're on main, and make sure main is up to date (git pull). Otherwise, your branch will start from the wrong point.

Step 06 / 15

Switch branches: git switch

$ git switch <branch-name>

$ git switch fix/mobile-menu

Switched to branch 'fix/mobile-menu'

When you switch branches, Git updates the files in your working directory to match that branch. It's normal to see files change or disappear: they still exist on the other branch.

The most common shortcut: create a branch and switch to it in a single command, with -c (create):

$ git switch -c feature/gallery

Switched to a new branch 'feature/gallery'

Concept

HEAD: the marker that shows where you are. Usually, HEAD points to your current branch. When you commit, the branch moves forward, and HEAD follows. That's the HEAD you see in (HEAD -> main) in the output of git log.

Before the commit

A
HEAD
B
main

After the commit

A
B
HEAD
C
main

C = new commit

When you commit, the branch moves to the new commit, and HEAD moves with it.

Tip

In many tutorials, you'll see git checkout <branch> and git checkout -b <branch>. That's the older way, and it still works. git switch was created to be clearer.

Warning

Before switching branches, commit your work in progress. Otherwise, Git may refuse to switch (so it won't overwrite your work), or bring your changes along to the other branch.

Which command creates a branch AND switches to it?

Step 07 / 15

Choose good branch names

A branch name should describe what you're working on. The most common convention: a prefix, a slash, then a short description with hyphens.

  • feature/ for a new feature: feature/contact-page
  • fix/ for a bug fix: fix/mobile-menu
  • docs/ for documentation: docs/readme-install
  • chore/ for maintenance: chore/update-dependencies

Practice

Avoid spaces and accented letters in branch names. Use lowercase letters and hyphens.

Step 08 / 15

Rename a branch

A typo in the name? Rename the branch with the -m (move) option:

$ git branch -m <old-name> <new-name>

$ git branch -m feature/galery feature/gallery

If you're already on the branch you want to rename, just give the new name:

$ git branch -m <new-name>

Step 09 / 15

Delete a branch

Once a branch is merged, you no longer need it. Delete it with the -d (delete) option:

$ git branch -d <branch-name>

$ git branch -d fix/mobile-menu

Deleted branch fix/mobile-menu (was 7a3e9c2).

If the branch has commits that haven't been merged, Git refuses to delete it, to protect you:

$ git branch -d test/new-font

error: the branch 'test/new-font' is not fully merged
hint: If you are sure you want to delete it, run 'git branch -D test/new-font'

If you're sure you want to abandon that work, force the deletion with -D (uppercase):

$ git branch -D test/new-font

Warning

-D deletes the branch even if its work was never merged. Those commits become very hard to recover. Only use it for work you really want to throw away.

Tip

You can't delete the branch you're currently on. Switch to another branch first, for example with git switch main.

Which option deletes a branch only if its work was merged?

Step 10 / 15

Merge branches: git merge

Done with your branch? Bring its work into main with git merge. The rule to remember: switch to the branch that receives the work, then merge in the branch that brings it.

$ git merge <branch-to-merge>

# 1. Switch to the receiving branch

$ git switch main

# 2. Merge the finished branch

$ git merge fix/mobile-menu

Updating 8c4e2f1..7a3e9c2
Fast-forward
 style.css | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

The commits from fix/mobile-menu are now part of main. The branch still exists: you can delete it with git branch -d.

Depending on the situation, Git merges in one of two ways.

Case 1: the fast-forward merge. main hasn't moved since you created your branch. Git simply moves the main label forward to your branch's last commit. No new commit is created.

Before

A
B
main
C
D
feature

After · main moves forward

A
B
C
feature
D
main
main hasn’t moved, so Git just slides the label forward to the tip. No new commit is created.

Case 2: the merge commit. main got new commits while you were working. Git creates a new commit that joins the two lines. This commit has two parents.

ABCDEMfeaturemainM = merge commit (2 parents)
Both branches have moved on, so Git creates a merge commit M with 2 parents.

$ git merge feature/gallery

Merge made by the 'ort' strategy.
 gallery.html | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)

Tip

For a merge commit, Git may open an editor for the message. The suggested message (Merge branch 'feature/gallery') is perfectly fine: save and close the editor.

Concept

If both branches changed the same line of the same file, Git can't choose for you: that's a merge conflict. You'll learn how to resolve it in chapter 5.

You want to bring feature/gallery into main. Where should you be before running git merge feature/gallery?

Step 11 / 15

Visualize branches: git log --graph

To see branches and their commits as a graph in the terminal:

$ git log --oneline --graph --all

*   c4d8e2a (HEAD -> main) Merge branch 'feature/gallery'
|\
| * 2b7f1e9 (feature/gallery) Add photo gallery
* | 7a3e9c2 Fix the mobile menu
|/
* 8c4e2f1 Add contact form

How to read it:

  • Each * is a commit.
  • The lines | / \ connect the commits: you can see where branches split off and come back together.
  • The names in parentheses are branch names. HEAD -> main shows where you are.

Tip

Tools like GitHub Desktop, or the Git Graph extension for VS Code, draw this graph with colors and lines. It's the same information.

Step 12 / 15

Recap: branches

1

git switch main, then git pull: you start from an up-to-date main

2

git switch -c feature/my-feature: you create your branch

3

git add and git commit: you work on your branch

4

git switch main, then git merge feature/my-feature: you merge

5

git branch -d feature/my-feature: you clean up

Your cheat sheet for this chapter:

$ git branch # list local branches

$ git branch -a # also list remote branches

$ git branch <name> # create a branch

$ git switch <name> # switch branches

$ git switch -c <name> # create and switch to it

$ git branch -m <old> <new> # rename

$ git branch -d <name> # delete (if merged)

$ git branch -D <name> # force-delete

$ git merge <name> # merge into the current branch

$ git log --oneline --graph --all # see the graph

git branch
— List branches
git switch -c
— Create a branch and switch to it
git branch -m
— Rename a branch
git branch -d
— Delete a merged branch
git merge
— Merge into the current branch

Step 13 / 15

Common mistakes

  • Merging from the wrong branch: git merge brings the work into the branch you're on. Check with git status before running git merge.
  • Accidentally creating a branch from a branch other than main: your new branch carries commits that have nothing to do with it.
  • Working directly on main: even for a small change, a branch is safer.
  • Switching branches with uncommitted changes: commit them first.
  • Using -D out of habit: prefer -d, which warns you if work hasn't been merged.

Step 14 / 15

Bonus: under the hood

Tip

Optional section for the curious. You can skip straight to the quiz.

A branch really is just a label: it's a small text file containing a commit's hash. You can read it:

$ cat .git/refs/heads/main

c4d8e2a9f1b3e5d7c9a2b4f6e8d0c1a3b5e7f9d2

When you commit on main, Git simply replaces this hash with the new commit's hash. That's why creating a branch is instant.

HEAD is a file too. It contains the name of your current branch:

$ cat .git/HEAD

ref: refs/heads/main

Warning

Detached HEAD: if you check out a commit directly instead of a branch (for example with git checkout 3f2a1b4 to look at an old version), HEAD points to that commit and no longer to a branch. You can look around safely. But if you commit, no branch keeps track of those commits. To get back safely: git switch main. To keep what you did: git switch -c new-branch.

Step 15 / 15

Test your knowledge

Check that you know how to create, switch and merge branches. Click the answer you think is correct: every answer comes with an explanation.

Quiz · Chapter 4

1. What is a Git branch?

2. Which command creates the fix/menu branch AND switches to it?

3. You want to bring the work from feature/gallery into main. What do you do?

4. git branch -d test won't delete the branch. Why?

5. When does Git do a fast-forward merge?

6. In git log --oneline, what does (HEAD -> main) mean?

Chapter 4 of 5

The investigation is just getting started. The next clue is waiting...

Your feedback matters

Help us improve this course by sharing your thoughts.

So we can follow up if needed.