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.