Appearance
13.11.2 — Branches: Try Something Without Risking the Rest
The shop works. Customers are using it. Your manager asks for a refund feature, and it will take a week.
During that week, someone will find a bug in the checkout and need to fix it today. If your half-finished refund code is mixed into the same files, the fix cannot go out until the refund feature is done.
A branch solves this. It gives you a private line of work. You build the refund feature on your branch while everyone else keeps working on the main line, and nothing you do can break theirs. When the feature is ready, you bring it back.
Branches are the reason Git won. In older tools, a branch meant copying the whole project, so people avoided them. In Git a branch costs almost nothing, so you make one for every task.
1. What a branch really is
Most people picture a branch as a copy of the project. It is not a copy. It is a label stuck on one commit.
Here is the history from the last page. Three commits, and one label called main on the newest one.
When you create a branch, Git writes one more label on the commit you are standing on. That is all. No file is copied. No commit is made.
text
$ git branch
* main
$ git branch refunds
$ git branch
* main
refundsgit branch with no name lists your branches. The star shows which one you are on. git branch refunds creates a new branch called refunds.
You now have two labels pointing at the same commit. That is why creating a branch is instant, and why you can have a hundred of them without slowing anything down. Chapter 13.11.5 shows that a branch is literally a tiny text file holding one commit id.
2. HEAD: which label you are standing on
You have two branches but you are only on one of them. Git needs to remember which. It uses HEAD.
HEAD points at the branch you are on. When you commit, the branch that HEAD points at moves forward. The other branches stay put.
To move to another branch, use git switch:
text
$ git switch refunds
Switched to branch 'refunds'HEAD points at a label, and the label points at a commit. git switch only moves HEAD to a different label. Git then rewrites your files to match that commit.Only HEAD moved. The commits and the labels stayed exactly where they were. But something else happened that matters: Git rewrote the files in your folder to match the commit you switched to. If the other branch has a file this one does not, that file appears or disappears from your folder.
You can see it for yourself. Here is the folder while on refunds, after we add a file and commit it, and then the folder after switching back:
text
$ printf 'export function canRefund(daysSinceOrder: number): boolean {\n return daysSinceOrder <= 30;\n}\n' > refund.ts
$ ls
README.md cart.ts refund.ts
$ git add refund.ts
$ git commit -m "Add refund window rule"
[refunds 13e148a] Add refund window rule
1 file changed, 3 insertions(+)
create mode 100644 refund.ts
$ git switch main
Switched to branch 'main'
$ ls
README.md cart.tsrefund.ts is gone from the folder. It has not been deleted. It is safe in the refunds branch, and it reappears the moment you switch back. Your editor may flash as files change under it. That is normal.
A note on older commands. Before 2019 the command for both switching branches and discarding file changes was git checkout. Doing two unrelated things with one command caused many accidents, so Git 2.23 added git switch (move between branches) and git restore (undo file changes). You will still see git checkout main and git checkout -b new in older tutorials. They work the same. Prefer the new ones.
3. Create and switch in one step
You almost always want to create a branch and move to it. One command does both:
bash
git switch -c refunds # -c means "create"Other commands you will use daily:
bash
git branch # list local branches
git branch -vv # list them with their latest commit and upstream
git switch - # jump back to the branch you were on before
git branch -m old new # rename a branch
git branch -a # include branches from the remote tooNaming. Branch names are free text, but teams use a pattern so you can read them at a glance: feature/refunds, fix/checkout-rounding, chore/upgrade-node. Use lowercase, hyphens instead of spaces, and a short phrase that says what the branch is for. Avoid names like test or my-branch.
4. Committing on a branch
Commits on a branch work exactly as before. The only difference is which label moves.
main stays exactly where it was, so the experiment cannot disturb it.We made two commits on feature. The feature label moved forward twice. The main label did not move. So main is still exactly the version that was working before you started. That is the safety a branch gives you.
You can draw the whole picture in your terminal:
text
$ git log --oneline --graph --all
* 13e148a Add refund window rule
* 085ab90 Start the shop--graph draws the lines between commits. --all shows every branch, not just the one you are on. Add them whenever you wonder what shape your history has.
5. Bringing the work back: merging
The refund feature is finished and tested. Time to put it into main. This is called a merge.
The rule is always the same: switch to the branch that should receive the work, then merge the other one into it.
bash
git switch main
git merge refundsWhat happens next depends on the shape of the history. There are two cases.
Case one: a straight line (fast-forward)
If main has not changed since you made your branch, there is nothing to combine. refunds is simply main plus some extra commits. Git just moves the main label forward to catch up.
text
$ git merge refunds
Updating 085ab90..13e148a
Fast-forward
refund.ts | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 refund.tsThe word Fast-forward tells you that is what happened. No new commit was made.
main has no new commits of its own, there is nothing to combine. Git just slides the main label forward along the line. No new commit is created.Read the figure from top to bottom. Before: main is on C, and feature is two commits ahead. After: main has slid forward to E. Both labels now point at the same commit, and the history is one straight line.
Case two: both lines moved (a merge commit)
Now suppose that, while you worked on discounts, a colleague also added a commit to main. The history has split in two.
text
$ git log --oneline --graph --all
* 682e6c2 Add discount helper ← on the discounts branch
| * 8ad1b89 Describe the project ← on main
|/
* 13e148a Add refund window rule ← where they split
* 085ab90 Start the shopGit cannot just slide a label forward, because each side has commits the other lacks. So it combines them and records the result as a new commit with two parents.
text
$ git merge discounts --no-edit
Merge made by the 'ort' strategy.
discount.ts | 3 +++
1 file changed, 3 insertions(+)
create mode 100644 discount.ts
$ git log --oneline --graph --all
* 15864ba Merge branch 'discounts'
|\
| * 682e6c2 Add discount helper
* | 8ad1b89 Describe the project
|/
* 13e148a Add refund window rule
* 085ab90 Start the shopThe new commit at the top is the merge commit. In the figure it is the circle M. Its two arrows go to the two branch tips it joined.
You can prove it has two parents. Print the commit:
text
$ git cat-file -p HEAD
tree dc3438c976e0298f4365356c314ad155dc7b3d88
parent 8ad1b89592956934364fcc6ed349881fc7631d0b
parent 682e6c2b229545a328a21567cab7d5e82f85fad1
author Ana Ruiz <ana@example.com> 1793189881 +0000
committer Ana Ruiz <ana@example.com> 1793189881 +0000
Merge branch 'discounts'Two parent lines. A normal commit has one. The message Merge branch 'discounts' was written by Git. Without --no-edit, Git opens your editor so you can change it; you can usually just save and close.
The phrase 'ort' strategy is the name of the algorithm Git used to combine the two sides. You do not need to choose it. Chapter 13.11.6 explains it.
Two options worth knowing:
bash
git merge feature --no-ff # always make a merge commit, even if a fast-forward was possible
git merge feature --ff-only # fast-forward or refuse; never makes a merge commit--no-ff keeps a visible record that a group of commits belonged together as a feature. --ff-only is a safety setting: "only merge if it is a clean straight line, otherwise stop and let me think."
6. When Git cannot merge by itself: conflicts
Git merges the two sides automatically as long as they changed different parts of the project. A change to refund.ts on one branch and README.md on another is fine.
A merge conflict happens when both branches changed the same lines. Git cannot know which version you want, so it stops and asks you.
Here is a real one. On main the tax rate was lowered to 18%. On the tax-rise branch it was raised to 25%. Both edited the same line.
text
$ git merge tax-rise
Auto-merging cart.ts
CONFLICT (content): Merge conflict in cart.ts
Automatic merge failed; fix conflicts and then commit the result.Do not panic. This is not an error and nothing is broken. A conflict is Git saying: "I need a human here."
Step one: look at the state.
text
$ git status
On branch main
You have unmerged paths.
(fix conflicts and run "git commit")
(use "git merge --abort" to abort the merge)
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: cart.tsgit status tells you which files are in conflict (both modified: cart.ts) and offers the way out: git merge --abort puts everything back exactly as it was before you started. You can always use that if you feel lost.
Step two: open the file. Git has written both versions into it.
text
$ cat cart.ts
export function total(prices: number[]): number {
return prices.reduce((a, b) => a + b, 0);
}
export function tax(amount: number): number {
<<<<<<< HEAD
return amount * 0.18;
=======
return amount * 0.25;
>>>>>>> tax-rise
}Read it like this. Everything between <<<<<<< HEAD and ======= is your version: the branch you are on. Everything between ======= and >>>>>>> tax-rise is their version: the branch you are merging in. The words "ours" and "theirs" mean exactly that.
Step three: decide, and edit the file. You have four choices:
- Keep yours (delete their lines).
- Keep theirs (delete yours).
- Combine them.
- Write something new. Often the right answer is neither. Here, you might phone the colleague and agree the rate is 20%.
Whatever you choose, delete all three marker lines (<<<<<<<, =======, >>>>>>>). If a marker stays in the file, you have committed broken code. A good habit is to search the file for <<<<<<< before you continue.
ts
export function tax(amount: number): number {
return amount * 0.2;
}If you want one whole side without editing by hand, there are shortcuts:
bash
git restore --ours cart.ts # take the version from the branch you are on
git restore --theirs cart.ts # take the version from the branch you are merging inStep four: tell Git the conflict is settled, then commit.
text
$ git add cart.ts
$ git status
On branch main
All conflicts fixed but you are still merging.
(use "git commit" to conclude merge)
Changes to be committed:
modified: cart.ts
$ git commit --no-edit
[main 53646f5] Merge branch 'tax-rise'git add here does not mean "add a new file". It means "I have resolved this file, treat it as final." Git will not let you commit while any file is still unmerged.
That is the entire process. Look at the state, open the file, decide, delete the markers, git add, git commit. If it goes wrong at any point, git merge --abort starts over.
To reduce conflicts: merge small branches often, keep each branch focused on one task, and pull the latest main into your branch regularly so the gap never grows large. A conflict in a branch that is one day old is a ten-minute fix. A conflict in a branch that is six weeks old can be a bad afternoon.
Most editors show conflicts with buttons ("Accept current", "Accept incoming", "Accept both"). VS Code does this. They do the same thing as editing the file by hand. A three-way merge tool can be launched with git mergetool. Chapter 13.11.6 also shows a setting that adds the original line to the markers, which often makes the right answer obvious.
7. Switching when you have unsaved changes
What if you have edited a file and not committed, and then you switch branch? Git has to rewrite your files, so it must not destroy your work. It follows two rules.
If the edit does not touch any file that differs between the branches, Git carries your change along. It tells you with a letter:
text
$ echo "wip" >> README.md
$ git switch rescue
Switched to branch 'rescue'
M README.mdThe M README.md means "modified file came with you".
If switching would overwrite your edit, Git refuses.
text
$ git switch a-branch
error: Your local changes to the following files would be overwritten by checkout:
cart.ts
Please commit your changes or stash them before you switch branches.
AbortingThis is Git protecting you. You have three ways out: commit the change (even a rough commit; you can tidy later), stash it (Chapter 13.11.7 shows git stash, which puts changes on a shelf), or throw it away with git restore cart.ts if you no longer want it.
8. Deleting branches
When a branch has been merged, it has done its job. Delete the label to keep the list tidy. The commits stay in history.
text
$ git branch --merged
discounts
* main
tax-rise
$ git branch -d tax-rise
Deleted branch tax-rise (was e80e34e).git branch --merged lists branches whose work is already in your current branch. Those are safe to remove. git branch --no-merged shows the opposite: branches with work that is not yet in.
-d is the safe delete. It refuses if the branch has commits that are not merged anywhere:
text
$ git branch -d idea
error: the branch 'idea' is not fully merged.
If you are sure you want to delete it, run 'git branch -D idea'-D (capital) deletes it anyway:
text
$ git branch -D idea
Deleted branch idea (was ff6ff8b).Notice that Git printed was ff6ff8b. That is the id of the commit the branch pointed at. If you deleted it by mistake, git branch idea ff6ff8b brings it back. If you did not write the id down, git reflog has it. Chapter 13.11.4 explains the reflog, which is Git's record of every movement of every label.
9. Detached HEAD: when you are standing on a commit, not a branch
Sometimes you want to look at an old version. You can switch to any commit by its id:
text
$ git switch --detach HEAD~2
HEAD is now at 15864ba Merge branch 'discounts'
$ git status
HEAD detached at 15864ba
nothing to commit, working tree cleanLook at what Git says: HEAD detached. Earlier, HEAD pointed at a branch label, and the label pointed at a commit. Now HEAD points straight at a commit, with no label in between. You are detached.
You can look around, run the code and test an old version. That is a good use of it. The trap is committing here.
text
$ git commit -a -m "Scratch work while detached"
$ git switch main
Warning: you are leaving 1 commit behind, not connected to
any of your branches:
d34ca4a Scratch work while detached
If you want to keep it by creating a new branch, this may be a good time
to do so with:
git branch <new-branch-name> d34ca4a
Switched to branch 'main'The commit exists, but no label points at it. When you left, nothing pointed at it any more, so it is effectively invisible. Git warns you and gives you the exact command to save it: git branch rescue d34ca4a.
The rule is simple. If you are detached and you make commits you want to keep, put a branch on them before you leave. If you were only looking, just switch back with git switch main.
What the interviewer will push on
Branching is a favourite topic because it shows whether you understand Git or only memorised commands.
"What is a branch in Git?" The interviewer wants one sentence that shows the model. A weak answer: "a copy of the code". A strong answer: "a movable pointer to a commit. Creating one writes a tiny file, which is why it is instant." Follow with how it moves: when you commit, the branch you are on advances to the new commit.
"What is the difference between a fast-forward merge and a merge commit?" They are checking that you know when each happens. Fast-forward: the target branch has no new commits, so Git moves its pointer, and no new commit exists. Merge commit: both branches have new commits, so Git creates a commit with two parents. Add that --no-ff forces a merge commit, which some teams want so a feature stays visible as a unit.
"What is a merge conflict and how do you resolve one?" The wrong answer is "I use the editor's button". The strong answer gives the cause (both sides changed the same lines), the process (read the markers, choose or combine, delete the markers, git add, git commit), and the escape hatch (git merge --abort). Mentioning how to avoid them (small branches, merge often) earns extra credit.
"What does HEAD mean? What is a detached HEAD?" HEAD is a pointer to where you are, normally to a branch. Detached means it points directly to a commit. Commits made there are not on any branch, so they can be lost; the fix is git branch name before switching away.
"What is the difference between git switch and git checkout?" checkout did several unrelated jobs. switch changes branches and restore undoes file changes. The old command still works, so naming the new pair shows you follow how the tool improves.
One thing to volunteer: say that a branch is cheap because it is only a label, so you make one for every task. It shows you understand the design rather than reciting rules.
Recall
- A branch is a movable label on one commit, not a copy of the project. Creating one writes a tiny file, so it is instant and free.
HEADpoints at the branch you are on. When you commit, that branch's label moves forward; the others stay put.git switch namemovesHEAD, and Git rewrites your files to match.git switch -c namecreates and switches.git branchlists,-vvshows details,-mrenames,-ddeletes if merged,-Ddeletes regardless.- To merge: switch to the branch that receives the work, then
git merge other. - Fast-forward (no new work on the target): Git only slides the label, no new commit. Merge commit (both sides moved): a new commit with two parents.
--no-ffforces a merge commit;--ff-onlyrefuses anything else. - A merge conflict is when both sides changed the same lines. Git writes both versions between
<<<<<<<,=======and>>>>>>>. Choose or combine, delete the three markers,git addthe file,git commit.git merge --abortundoes the attempt. - Switching with unsaved changes: Git carries them if nothing conflicts, and refuses if the checkout would overwrite them. Commit, stash, or restore.
- A detached HEAD is
HEADpointing at a commit with no label. Commits made there are lost unless you put a branch on them (git branch name <id>).
Self-test: Why is creating a branch instant? · What changes in your folder when you run git switch? · When does a merge produce a fast-forward, and when a merge commit? · What are the four steps of resolving a conflict, and which command backs out? · Why can commits on a detached HEAD disappear?
Next: 13.11.3 moves your repository off your own laptop: what a remote is, how clone, fetch, pull and push differ, and why a push is sometimes refused.