Branches - Parallel Universes
Branches
Scenario: You're mid-way through a risky new feature when an urgent bug needs fixing on the live site. You don't want your half-done feature going out with it. Branches solve exactly this: work on the feature in isolation, switch away to fix the bug, and come back exactly where you left off.
A branch is an independent line of commits. The default branch in a new repo is usually called main. Mechanically, a branch is almost nothing: it's just a small named pointer to one specific commit. When you make a new commit while "on" a branch, Git creates the commit and then simply moves that branch's pointer forward to point at it. That's the entire trick - which is also why creating a branch is instant and nearly free, unlike, say, copying an entire project folder.
| Command | Does |
|---|---|
git branch | List branches (* marks current) |
git branch feature | Create a branch (pointing at your current commit) |
git switch feature | Switch to it (modern) |
git switch -c feature | Create and switch |
git checkout feature | Switch to it (older syntax) |
git branch -d feature | Delete a merged branch |
$ git switch -c feature-login
Switched to a new branch 'feature-login'
$ git branch
* feature-login
main
Analogy: Branching is a parallel universe for your code. Commits you make onfeature-logindon't touchmainat all -main's pointer stays exactly where it was - until you deliberately decide to merge them back together.
Tip:git switch(create/change branches) andgit restore(discard file changes) are the modern, purpose-built replacements for the older, overloadedgit checkout, which did both jobs (and a third - checking out a specific commit) depending on what you passed it, confusing generations of beginners. You'll still seecheckouteverywhere in older tutorials; it still works, butswitch/restoreare clearer about intent.
Warning: If you check out a specific commit hash directly (git checkout a1b2c3d) instead of a branch name, you land in detached HEAD state - you're no longer "on" any branch. Any new commits you make there aren't attached to a branch pointer and can become hard to find later if you switch away without creating a branch first. If Git ever warns "You are in 'detached HEAD' state", eithergit switch -c rescue-branchto give your work a home, or justgit switch mainto get back to safety if you didn't mean to commit anything.