Creating and Switching Branches
Asha wants to try a vegan pancake recipe, but the current one works and her brother cooks from it every Sunday. She needs a place to experiment where mistakes cannot touch the good version. In Git that place is a branch, and making one takes less than a second.
The rule
A branch is a movable label on a commit; new commits carry the current label forward.
A branch is not a copy of your files. It is a tiny named pointer to one commit. main is simply the branch you started on. When you commit, the branch you are on moves forward to the new commit, and the others stay where they were.
git branch # list branches; * marks the current one
git branch vegan-pancakes # create a branch here, but stay put
git switch vegan-pancakes # move onto it
git switch -c vegan-pancakes # create and move in one stepOlder tutorials use git checkout for the same jobs: git checkout vegan-pancakes switches and git checkout -b vegan-pancakes creates and switches. Both still work. git switch was added later because checkout also does unrelated things, such as restoring files, and the single-purpose command is harder to misuse.
What happens when you switch:
- Git updates the files in your working directory to match the tip commit of that branch.
HEAD, Git's "you are here" marker, now points at the new branch.- Uncommitted changes come with you if they do not clash with the target branch. If they would be overwritten, Git refuses to switch until you commit them or set them aside.
Branch names follow simple rules: no spaces, and short, descriptive, hyphenated names work best, such as vegan-pancakes or fix-chai-typo.
The shortcut
Before starting any new piece of work, ask "If this goes wrong, should main notice?" If the answer is no, which is almost always, run git switch -c <name> first and only then start editing.
Where am I?
git branchshows* main. The labelmainpoints at commit9b2d7e4.
The trap is editing on main and only afterwards remembering to branch. If you have not committed yet, no harm is done: git switch -c <name> carries your uncommitted edits onto the new branch, and you commit them there. Once you have committed on main, fixing it takes more work.
Drills
Answer fast — trust the rule.
What is a Git branch?
Which single command creates fix-chai-typo and switches to it?
Asha is on vegan-pancakes and makes a commit. What happens to main?
In the output of git branch, what does * mean?
Which older command does the same as git switch -c vegan-pancakes?
Remember
- A branch is a movable label on a commit; new commits carry the current label forward.
- Branch before you start:
git switch -c <name>. git checkoutandgit checkout -bare the older forms ofgit switchandgit switch -c.
