Working with branches

Intermediate

Introduction

Real projects always have several things going on: a new feature, an urgent bug fix, an experiment. Branches let each of them happen in its own line of history, so the main branch stays working while work in progress is incomplete. Because branches in Git are just movable names, creating one is instant, and a typical developer creates and deletes several a day.

How it works

When you create a branch, it points at the same commit as HEAD. When you commit, only the current branch moves to the new commit. So after committing on feature and then on main, the history diverges: two branches with a common past and different new commits. The commits form a graph, which git log --oneline --graph --all draws.

git branch                      # list branches, * marks the current one
git branch feature              # create a branch at HEAD
git switch feature              # make it current
git switch -c fix-footer        # create and switch in one step
git branch -d fix-footer        # delete a branch that is merged
git branch -D experiment        # force-delete a branch with unmerged work
git branch --merged main        # branches already contained in main

A branch is merged into main when its tip can be reached from main's tip: all its commits are part of main. Such a branch can be deleted without losing anything. A branch that is not merged is ahead by the commits reachable from it but not from main; git branch -d refuses to delete it.

Branch names follow rules. They cannot contain spaces or any of ~ ^ : ? * [ \, cannot contain .. or @{, cannot start with -, and cannot have a part (between slashes) that starts with . or ends with .lock. Slashes group related branches: feature/search, fix/login-timeout, release/2.1.

Example

commits = {}
branches = {}
current = "main"


def commit(message):
    oid = f"c{len(commits) + 1}"
    commits[oid] = (branches.get(current), message)
    branches[current] = oid
    print(f"[{current} {oid}] {message}")


def history(name):
    oid, out = branches[name], []
    while oid:
        out.append(oid)
        oid = commits[oid][0]
    return out


commit("Start the app")
commit("Add a home page")
branches["feature"] = branches[current]
current = "feature"
print("switched to a new branch 'feature'")
commit("Add search")
commit("Improve search results")
current = "main"
print("switched to branch 'main'")
commit("Fix the footer")
for name in sorted(branches):
    print(("* " if name == current else "  ") + name, branches[name], " <- " + " <- ".join(history(name)[1:]))
Open in compiler

Line by line

  1. Commits get simple ids c1, c2, … and remember their parent and message.
  2. Committing moves only the current branch, exactly as in Git.
  3. feature starts at c2 and gets two commits of its own.
  4. Back on main, a new commit c5 also has c2 as its parent: the history has diverged.
  5. The listing shows each branch's tip and the chain of parents behind it.

Expected result

[main c1] Start the app
[main c2] Add a home page
switched to a new branch 'feature'
[feature c3] Add search
[feature c4] Improve search results
switched to branch 'main'
[main c5] Fix the footer
  feature c4  <- c3 <- c2 <- c1
* main c5  <- c2 <- c1

In the real world

Teams usually follow a branching workflow: in GitHub flow, every change happens on a short-lived branch that is merged into main through a pull request. Larger projects keep release branches for maintenance and may use prefixes such as feature/ and hotfix/. Hosting services can protect main so that nobody can commit to it directly.

Common mistakes

  • Working on main by accident; check git status or your prompt before committing.
  • Keeping branches alive for weeks, so they drift far from main and merge painfully.
  • Force-deleting a branch with -D without checking that its work is merged.
  • Using spaces or special characters in branch names.

Best practices

  • Create a new branch for each feature or fix, named after its purpose.
  • Merge or rebase often to keep branches close to main.
  • Delete branches after they are merged, locally and on the remote.

Summary

Branches are movable names; committing advances only the current branch, so separate lines of work form a graph. A branch is merged into another when its tip is reachable from the other's tip; otherwise it is ahead by its own commits. Branch names must follow Git's rules, and slashes help organize them.

Quick check

1. You commit while on feature. What moves?
2. When is a branch merged into main?
3. Which branch name is valid?
4. What does git branch -d do with an unmerged branch?

Key takeaways

  • Committing moves only the current branch; other branches stay where they were.
  • A branch whose tip is reachable from main is merged and can be deleted safely.
  • Branch names cannot contain spaces, "..", or characters such as ~ ^ : ? * [ \.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.