Git Branch

Updated · 13 min read
easyGit 2.53gitgit-branchbranchesinterview

Imagine a cook trying out a new recipe. They don't change the restaurant's menu while they experiment. They work on a copy in a notebook, try it a few times, and only when the dish is right does it go on the menu. If the experiment fails, the menu was never touched.

A branch is that notebook copy for your project. On a branch, you can build a new feature or try an idea while main stays exactly as it was. Teammates can each work on their own branch at the same time. When the work is ready, it is merged back, and if it doesn't work out, the branch is simply deleted.

In this lesson, you will learn what a branch really is in Git, and how to create, list, rename and delete branches.

What a Branch Really Is

In many older version control systems, a branch was a full copy of the project. In Git, a branch is much smaller: a name that points to one commit. That's all. When you make a commit on a branch, Git moves the branch's name forward to the new commit.

main, the branch you have been using since your first commit, is an ordinary branch like any other. Git creates it for you with your first commit.

HEAD tells Git which branch you are on. When you commit, the branch that HEAD points to is the one that moves forward.

A branch is a name that points to a commit

The Starting Point

Terminal
mkdir fee-tracker
cd fee-tracker
git init --quiet
echo "Fee Tracker" > README.md
git add README.md
git commit --quiet -m "Add project README"
echo 'Term 1 fee: $12,000' > fees.txt
git add fees.txt
git commit --quiet -m "Add the term fees"
echo 'Late fee: $250' >> fees.txt
git commit --quiet -am "Add the late fee"
git branch
Output
* main

git branch with no arguments lists your branches. There is only main so far, and the * marks the branch you are on.

Create a Branch

Advitha is going to build receipt printing. git branch followed by a name creates a branch at the commit you are on:

Terminal
git branch receipts
git branch
git log --oneline
Output
* main
  receipts
4c2a088 (HEAD -> main, receipts) Add the late fee
4009644 Add the term fees
dd34d8a Add project README

Two things to notice:

  1. The * is still on main. Creating a branch doesn't switch to it.
  2. In the log, (HEAD -> main, receipts) shows that both branches point to the same commit. No files were copied. The new branch is only a new name.

Branches Move Apart

Navika keeps working on main and adds the hostel fee:

Terminal
echo 'Hostel fee: $9,000' >> fees.txt
git commit --quiet -am "Add the hostel fee"
git log --oneline --all
Output
c918f8d (HEAD -> main) Add the hostel fee
4c2a088 (receipts) Add the late fee
4009644 Add the term fees
dd34d8a Add project README

main moved forward with the new commit, because HEAD points to main. receipts stayed where it was. --all makes git log show the commits of every branch, not only the current one.

Now Advitha switches to receipts and commits there. git switch has its own lesson next. Here it only moves HEAD to the other branch, and --quiet hides its "Switched to branch" message:

Terminal
git switch --quiet receipts
echo "Receipt No. 1" > receipts.txt
git add receipts.txt
git commit --quiet --author="Advitha Anamaneni <advitha@example.com>" -m "Add receipt numbers"
git log --oneline --graph --all
Output
* 5163e8a (HEAD -> receipts) Add receipt numbers
| * c918f8d (main) Add the hostel fee
|/
* 4c2a088 Add the late fee
* 4009644 Add the term fees
* dd34d8a Add project README

The graph shows the two lines of work. Both start from "Add the late fee", and each branch has a commit the other doesn't. On receipts, fees.txt has no hostel fee, and on main, there is no receipts.txt. Each branch is its own version of the project.

List Branches

-v (verbose) adds each branch's newest commit:

Terminal
git switch --quiet main
git branch -v
Output
* main     c918f8d Add the hostel fee
  receipts 5163e8a Add receipt numbers
CommandIt lists
git branchLocal branches, * on the current one
git branch -vThe same, with each branch's newest commit
git branch -rRemote-tracking branches, such as origin/main
git branch -aLocal and remote-tracking branches
git branch --mergedBranches whose work is already contained in the current branch
git branch --no-mergedBranches with commits the current branch doesn't have yet
git branch --show-currentOnly the name of the current branch

-r and -a matter once you work with a remote repository, which is the topic of the lessons on remotes.

Which Branches Are Finished?

Navika once made a branch for a small idea and never committed on it. It points to an older commit of main:

Terminal
git branch old-idea HEAD~1
git branch --merged
Output
* main
  old-idea
Terminal
git branch --no-merged
Output
  receipts

old-idea points to a commit that is already part of main, so it counts as merged: deleting it loses nothing. receipts has a commit main doesn't have, so it is not merged. Use these two lists to tidy up old branches safely.

Rename a Branch

-m (move) renames a branch. Advitha prefers a clearer name:

Terminal
git branch -m receipts receipt-printing
git branch
Output
* main
  old-idea
  receipt-printing

To rename the branch you are on, git branch -m <new-name> is enough. If the branch was already pushed, renaming it locally doesn't rename it on the remote. That takes a push of the new name and a deletion of the old one, covered with remotes.

Delete a Branch

-d deletes a branch, but only if its work is merged:

Terminal
git branch -d old-idea
Output
Deleted branch old-idea (was 4c2a088).

Git prints the commit the branch pointed to. Now try the same with Advitha's branch, whose commit is not on main:

Terminal
git branch -d receipt-printing
Output
error: the branch 'receipt-printing' is not fully merged
hint: If you are sure you want to delete it, run 'git branch -D receipt-printing'
hint: Disable this message with "git config set advice.forceDeleteBranch false"

Git refuses, because deleting the branch would leave "Add receipt numbers" on no branch at all. When you are sure, capital -D forces it. Here, Navika makes a throwaway branch with one commit and deletes it with -D:

Terminal
git switch --quiet -c experiment
echo "discount idea" > discount.txt
git add discount.txt
git commit --quiet -m "Try a discount"
git switch --quiet main
git branch -D experiment
git branch
Output
Deleted branch experiment (was 9b45ad2).
* main
  receipt-printing

You can't delete the branch you are on. Switch to another branch first.

Syntax

Terminal
git branch [<name> [<start-commit>]]
git branch -m [<old-name>] <new-name>
git branch -d | -D <name>
CommandIt is used to
git branch <name>Create a branch at the current commit
git branch <name> <commit>Create a branch at another commit
git branch -m <old> <new>Rename a branch
git branch -d <name>Delete a merged branch
git branch -D <name>Delete a branch even if it isn't merged

Naming Branches

A branch name can contain letters, numbers, -, _, . and /, but no spaces and no characters such as ~, ^, : or ?. Most teams use a short prefix that says what kind of work the branch holds, followed by a few words:

PrefixUsed forExample
feature/New featuresfeature/receipt-printing
fix/ or bugfix/Bug fixesfix/late-fee-rounding
hotfix/Urgent fixes for productionhotfix/payment-crash
docs/Documentationdocs/install-guide
release/Preparing a releaserelease/2.1

Many teams also add the issue number, as in fix/142-late-fee-rounding. The slash is only part of the name, but many tools show such branches grouped in folders.

Terminal
git branch feature/late-fee-rules
git branch "my branch"
Output
fatal: 'my branch' is not a valid branch name
hint: See 'git help check-ref-format'
hint: Disable this message with "git config set advice.refSyntax false"

The first name is fine. The second fails because of the space.

Common Mistakes

Expecting git branch <name> to switch to the new branch. It only creates it. Use git switch -c <name> to create and switch in one step.

Committing on the wrong branch. Check the * in git branch, or the first line of git status, before you start work. The "Git Reset" lesson shows how to move a commit that landed on the wrong branch.

Using -D out of habit. -d protects you from deleting unmerged work. Use -D only after you've read the warning and are sure.

Keeping dozens of finished branches. Use git branch --merged regularly, and delete what is listed.

Thinking a branch is a copy of the files. It is only a pointer. That is why creating and switching branches is so fast, even in a huge project.

Under the Hood

A branch is stored as a tiny text file under .git/refs/heads/, whose content is the full ID of the commit it points to:

Terminal
cat .git/refs/heads/main
git rev-parse main
cat .git/HEAD
Output
c918f8dec2bcb2a317b4d5c80bc7a10bc3c438e5
c918f8dec2bcb2a317b4d5c80bc7a10bc3c438e5
ref: refs/heads/main

The file holds 40 characters and a new line, 41 bytes, whatever the size of the project. Creating a branch writes one such file, and committing rewrites it with the new ID. .git/HEAD holds the name of the current branch, which is how Git knows which file to update. A branch name with a slash, such as feature/late-fee-rules, becomes a folder feature with a file late-fee-rules in it. (In large repositories, Git sometimes packs many of these files into one file, .git/packed-refs, but they work the same.)

Interview Corner

What is a branch in Git?

A movable pointer to a commit, stored as a small file containing that commit's ID. When you commit on a branch, it moves forward to the new commit. Creating a branch copies no files, which makes branches cheap enough to use for every task.

What is the difference between git branch -d and git branch -D?

-d deletes a branch only if its commits are merged into the current branch (or its upstream). -D deletes it regardless, which can leave commits on no branch. Those can be found again for a while through git reflog.

How do you list branches that are already merged?

git branch --merged lists branches whose tips are reachable from the current branch, so they can be deleted safely. git branch --no-merged lists the ones with work not yet merged.

How do you rename a branch?

git branch -m <old> <new>, or git branch -m <new> for the current branch. For a branch already on a remote, push the new name with git push -u origin <new> and delete the old one with git push origin --delete <old>.

What happens when you create a branch?

Git writes a new ref (.git/refs/heads/<name>) containing the current commit's ID. Nothing else changes: you stay on the current branch, and no files are copied.

Practice

Challenge: predict the lists. In the same repository, you are on main. Create a branch fix/rounding at the current commit, then create a branch docs/readme and make one commit on it that adds Run the app. to README.md. Switch back to main and print git branch --merged and git branch --no-merged.

What does Git print? Before you open the solution, decide which list each of the four branches (docs/readme, feature/late-fee-rules, fix/rounding, receipt-printing) appears in.

Show solution
Terminal
git branch fix/rounding
git switch --quiet -c docs/readme
echo "Run the app." >> README.md
git commit --quiet -am "Explain how to run the app"
git switch --quiet main
echo "Merged:"
git branch --merged
echo "Not merged:"
git branch --no-merged
Output
Merged:
  feature/late-fee-rules
  fix/rounding
* main
Not merged:
  docs/readme
  receipt-printing

feature/late-fee-rules and fix/rounding were created on main and have no commits of their own, so they are merged, together with main itself. docs/readme and receipt-printing each have a commit that main doesn't, so they are not merged.

Checkpoint. In a practice repository, create two branches for two different features, make a commit on each, and look at git log --oneline --graph --all. Then delete one with -d and see Git refuse, and decide whether -D is right.

Quick check: Git branch

4 questions
1What is a branch in Git?
2You run git branch receipts. Which branch are you on now?
3Why does git branch -d feature refuse to delete a branch?
4Which command lists branches that can be deleted without losing work?

Key Takeaways

Quick reference

CommandIt is used to
git branchList local branches
git branch -vList branches with their newest commits
git branch -aList local and remote-tracking branches
git branch <name>Create a branch
git branch <name> <commit>Create a branch at a commit
git branch -m <old> <new>Rename a branch
git branch -d <name>Delete a merged branch
git branch -D <name>Force-delete a branch
git branch --mergedList branches that are fully merged
git log --oneline --graph --allSee every branch as a graph

Was this tutorial helpful?

Lesson 27 of 106