Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 78 ยท Branching and Merging

Branches

Understand Git branches as movable pointers: create, list, switch, rename and delete them, learn what HEAD and a detached HEAD are, and name branches well.

Branching is the feature that made Git famous. In older version control systems a branch meant copying a whole directory tree, so people avoided it. In Git a branch is so cheap that professionals create several per day: one for each bug fix, each experiment, each feature. You try an idea on its own line of history, and if it works you bring it back; if it does not, you throw it away and nothing else is affected.

The reason it is cheap is simple, and it is the most important sentence in this lesson: a branch is just a movable pointer to one commit. It is not a folder, not a copy, not a container of commits. This lesson builds that mental model, then shows how to create, list, switch, rename and delete branches, what HEAD and a "detached HEAD" are, and how to name branches. If you have not yet seen how commits link to each other, read How Git Works first.

A branch is a pointer

Every commit knows its parent. Follow the parent links backwards and you get a history. A branch is a name that points at the tip (the newest commit) of such a chain. When you commit, Git creates the new commit with the current tip as its parent and then moves the branch name forward to the new commit.

gitGraph
    commit id: "A"
    commit id: "B"
    branch feature
    checkout feature
    commit id: "C"
    commit id: "D"
    checkout main
    commit id: "E"

Two lines of work that started from commit B: main moved on to E while feature added C and D. A branch is only a label that points at one commit.

TEXT
          A <โ”€โ”€ B <โ”€โ”€ C        main points at C
                       โ–ฒ
                      main

After "git branch feature":

          A <โ”€โ”€ B <โ”€โ”€ C        two names, one commit
                       โ–ฒ  โ–ฒ
                   main   feature

After one commit on feature:

          A <โ”€โ”€ B <โ”€โ”€ C <โ”€โ”€ D
                       โ–ฒ    โ–ฒ
                    main    feature

Nothing was copied when feature was created. Git wrote a tiny file containing a commit ID. We can see that file directly, which makes the idea concrete.

Bash A branch is a file that holds a commit ID

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Both branch files contain the same 40-character commit ID plus a newline (41 bytes). Creating a branch cost 41 bytes. The file .git/HEAD is different: it contains ref: refs/heads/main, which means "I am on the branch called main". We look at these files properly in References, HEAD and the .git Directory.

HEAD: where you are

HEAD is Git's "you are here" marker. Normally it points at a branch name, and that branch points at a commit. The commit that HEAD leads to is the one your working directory is based on, and it becomes the parent of your next commit. When you commit, the branch that HEAD points at is the one that moves.

So "the current branch" simply means "the branch HEAD points at". Switching branches means pointing HEAD at a different name and updating your files to match that commit.

Creating, listing and switching

Three commands cover everyday branching:

Command What it does
git branch List local branches; the current one has a *
git branch name Create name at the current commit, without switching
git switch name Move HEAD to name and update the working directory
git switch -c name Create name at the current commit and switch to it (-c is "create")

git switch arrived in Git 2.23 together with git restore. Before that, one overloaded command, git checkout, did both jobs, and you will still see it everywhere: git checkout name switches and git checkout -b name creates and switches. They work the same for branches. We use switch because its name says what it does.

Bash Create a branch, commit on it, and see the graph

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Read the graph from the top: the newest commit is first, and the lines show that history split after "Add more". main moved on with the typo fix, while feature/login has its own commit. The two lines of history now diverge. Notice the last part: when we switched back to feature/login, the file login.txt appeared in the directory, and it was gone while we were on main. Git rewrote your working directory to match the commit the branch points at. That is why switching branches is instant for small projects and why it can refuse to run when you have unsaved changes (see below).

git log --oneline --graph --decorate --all is the single most useful command for understanding branches. --all shows every branch, --graph draws the lines, --decorate prints branch names next to commits. Many people save it as an alias called lg; see Aliases and Everyday Productivity.

Switching with uncommitted changes

Git will not switch if doing so would overwrite your uncommitted work. If the files you changed are the same in both branches, Git carries your changes along. If they differ, Git stops:

Bash Switch refused when changes would be lost (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The real message is error: Your local changes to the following files would be overwritten by checkout: followed by the file name and advice to "commit your changes or stash them before you switch branches". Your options are to commit, to stash the changes, or to discard them. Never use --force here unless you truly want to lose the edit.

Looking at branches more closely

git branch has several useful variations:

  • git branch -v adds the latest commit's ID and subject for each branch.
  • git branch -vv also shows which remote branch each one tracks (more in Remotes).
  • git branch --show-current prints just the current branch name, handy in scripts.
  • git branch -a includes remote-tracking branches; git branch -r only those.
  • git branch --contains <commit> lists branches that include a commit.

Branches are listed alphabetically, not by recency; if you need recent first, use git branch --sort=-committerdate.

Renaming and deleting

Rename with -m (move). Delete with -d, which is the safe form: it refuses to delete a branch whose commits are not reachable from anywhere else, so you cannot lose work by accident. -D forces the deletion.

Bash Rename, delete safely, and force delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

draft had no commits of its own (it pointed at the same commit as main), so -d deleted it without complaint. experiment had a commit that no other branch contains, so -d refused with an error that says the branch "is not fully merged" and suggests git branch -D. Using -D really does remove the only name pointing at "Risky idea". The commit is not erased immediately; Git's reflog usually lets you get it back for a while. Notice also that deleting a branch deletes the pointer, never the commits that are reachable from other branches.

You cannot delete the branch you are on. Switch away first.

Starting a branch somewhere else

By default a new branch starts at your current commit, but you can name any starting point:

TEXT
git branch hotfix a1b2c3d      # at a specific commit
git switch -c hotfix v1.2.0    # at a tag
git switch -c review origin/feature   # from a remote-tracking branch
git branch rescue HEAD~3       # three commits before the current one

This is how you "go back" to start a fix from an older release. HEAD~3 is one of several ways to name commits; see Revision Syntax for the complete list.

Detached HEAD

Usually HEAD points at a branch. If you check out something that is not a branch, such as a commit ID, a tag or origin/main, HEAD points straight at a commit. This is a detached HEAD. Git prints a long warning about it, and many beginners panic, but the state is perfectly normal for looking around.

TEXT
Normal:    HEAD โ”€โ”€โ–ถ main โ”€โ”€โ–ถ C
Detached:  HEAD โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ถ B      (no branch name involved)

The danger is committing while detached. The new commit is not on any branch, so when you switch away nothing points at it. It becomes an orphan and eventually Git garbage-collects it. The fix is to give it a name before you leave.

Bash Commit on a detached HEAD, then rescue it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

While detached, git branch --show-current prints nothing. After we left, no branch contained the experiment, yet its ID still worked because Git has not collected it. Creating rescued at that ID gave it a permanent name. If you have already switched away and forgotten the ID, git reflog shows where HEAD has been; see The Reflog and Recovering Lost Work. The easiest habit: if you realize you are detached and want to keep working, run git switch -c new-name right there.

Naming branches

Git allows almost any name, but a team works better with conventions:

  • Use lowercase words separated by hyphens: fix-login-redirect, not Fix Login Redirect (spaces are illegal anyway).
  • Slashes create a folder-like hierarchy that tools understand: feature/search, bugfix/crash-on-start, release/2.4. Note that you cannot have both feature and feature/search, because one is a file and the other would need to be a folder in .git/refs/heads.
  • Put a ticket number or a short description in the name: feature/PROJ-123-export-csv.
  • Avoid names that look like options (leading -), contain .., end with .lock, or contain spaces, ~, ^, :, ?, * or [.
  • The main branch is conventionally main (older repositories use master). It is only a convention: Git treats it like any other branch. Which name git init uses is a setting; see Installing and Configuring Git.

Branches are local until you share them. Creating a branch does not create anything on a server. Pushing and tracking come in push, pull and Tracking Branches.

Pitfalls professionals know

  • Branches do not isolate files on disk. There is one working directory; switching rewrites it. If you need two branches checked out at the same time, use worktrees.
  • Untracked files travel with you. Git does not touch them when switching, so a build folder or scratch file appears on every branch. Use .gitignore for those.
  • A branch with the same name as a file can confuse commands. Put -- after the branch name when in doubt: git log feature -- path.
  • Long-lived branches drift. The longer a branch lives apart from main, the harder the later merge becomes. Keep branches small and merge often.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a Git branch, technically?

    A branch is a tiny reference holding one commit ID. Creating one copies nothing, which is why branches are cheap.
  2. 2. Which command creates a branch called fix and switches to it in one step?

    git switch -c creates the branch at the current commit and moves HEAD to it. git branch fix would create it without switching.
  3. 3. You run git branch -d experiment and Git says the branch is not fully merged. What should you do?

    -d protects commits that no other branch contains. -D forces the deletion and drops the only name pointing at those commits.
  4. 4. You are on a detached HEAD and make a commit. What happens if you switch to main without doing anything else?

    Nothing points at the new commit, so it is only reachable by its ID or the reflog until garbage collection. Name it with git switch -c or git branch before leaving.
  5. 5. Why can't you have both a branch named feature and a branch named feature/search?

    Local branches live in .git/refs/heads. A path cannot be a file (feature) and a directory (feature/search) at once.

Summary

  • A branch is a movable pointer to a commit; creating one costs almost nothing.
  • HEAD points at the current branch; committing moves that branch forward.
  • git switch -c name creates and switches; git branch lists, -m renames, -d deletes safely, -D forces.
  • Switching rewrites your working directory and refuses when it would overwrite uncommitted changes.
  • A detached HEAD is HEAD pointing at a commit; name your work with git switch -c before leaving it.
  • Name branches with lowercase words, hyphens and optional type/ prefixes.

Next: Merging Branches