Sub topic 2
A branch is a pointer to a commit
This chapter assumes you can run git init, git add, git commit, git status, and git log. It also assumes Git 2.23 or later, which added git switch. The goal is a working model of what a branch is, because every later operation (merge, rebase, delete, recover) follows from it.
What a branch contains
A branch is a small file that holds one commit ID. It holds no files and no copy of your project. When you commit while on a branch, Git creates the new commit and moves that branch's pointer to it.
You can see this directly. Local branches live under .git/refs/heads/, one file per branch.
git init pointer-demo
cd pointer-demo
git commit --allow-empty -m "first"
git commit --allow-empty -m "second"
cat .git/refs/heads/main
git rev-parse mainBoth of the last two commands print the same 40-character commit ID. If your default branch is named master, substitute that name. The --allow-empty flag lets you commit without staging files, so the demo needs no other setup.
Why branching is cheap
Creating a branch writes one 40-character ID to one file. Git does not copy any files, so the cost is the same in a repository of ten commits or ten million.
git branch feature/login
git branch -vBoth main and feature/login now point at the same commit. Nothing has diverged yet. The branches separate only when you commit on one of them.
git switch feature/login
git commit --allow-empty -m "add login form"
git log --oneline --all --decorateThe log shows feature/login one commit ahead of main. The main pointer did not move. Only the pointer of the branch you were on advanced.
The pointer moves forward
Arrows point from a commit to its parent. That direction matches how Git stores history: each commit knows where it came from, never where it leads.
Common errors
- Thinking a branch is a folder or a copy. Switching branches changes the files in your working directory to match the target commit. It does not swap between stored copies.
- Expecting the old branch to follow you. Committing on
feature/loginleavesmainwhere it was. - Believing deleting a branch deletes commits. It removes only the label. The commits stay in the repository until Git cleans up unreachable ones, which is why recovery is possible later.
Exercise
You are on feature/login, which was created from main. You make two commits. What does git rev-parse main print, compared with git rev-parse feature/login?
Show answer
main prints the commit ID it pointed at before you started, and feature/login prints the ID of your second new commit. The two IDs differ because only the checked-out branch's pointer moves when you commit.