Branching and switching
Work on changes in isolation with branches, then bring them together.
- Create and switch branches with git switch
- Explain why branches are cheap, isolated lines of work
- Merge a finished branch back into main
A branch is an independent line of work. You can try something — a feature, a fix, a risky idea — without touching the stable version, then either keep it or throw it away. Branches are the foundation of working safely, alone or with others (including agents whose work you want to review before it's official).
Create and switch
The modern, clear commands are git switch and git branch:
git branch # list branches; * marks the current one
git switch -c add-login # create a new branch and switch to it
# ...edit, add, commit on this branch...
git switch main # go back to the main line-c means "create." Without it, git switch <name> just moves to an existing
branch. (You may see git checkout in older material — switch is the newer,
less overloaded command for the same job.)
Why branches are cheap
A branch is essentially a lightweight pointer to a commit, so creating one is
near-instant and costs almost nothing. That cheapness is the point: make a branch
for every distinct piece of work. If it pans out, keep it; if not, delete it
(git branch -d add-login) and your main line never knew it existed.
Commits you make on a branch stay on that branch until you merge — main is
untouched while you experiment.
Bringing a branch back: merge
When a branch is done, merge it into main:
git switch main
git merge add-loginIf main hasn't changed in the meantime, git does a clean "fast-forward." If
both lines changed different files, git combines them automatically. If they
changed the same lines, you get a merge conflict — covered in the intermediate
Git module.
Do it yourself: git switch -c experiment, make a commit, then
git switch main and git log --oneline. Your experimental commit isn't
there — it's safely on the other branch. Merge it and watch it appear.
Where to go next
You can work in isolation and merge back. Next: working with remotes — sharing your repository with a server like GitHub so your work is backed up and collaborative.