Skip to content

🌿 Chapter 7: Branch Management — Parallel Universes

What is a Branch?

Imagine you're writing a novel, and halfway through you want to try making the protagonist turn evil. But you don't want to ruin the original storyline. What do you do? Open a "parallel universe" — that's a branch.

In Git, creating a branch costs almost nothing (it's just a pointer), but its power is immense:

  • Each feature can be developed independently without interference
  • Experimental code can live on a branch; if it fails, just delete it
  • Multiple people can develop different features simultaneously
  • The main branch always stays in a working state

Basic Branch Operations

bash
# View all branches
git branch
* main

# Create a new branch
git branch feature/user-login

# Switch to the new branch
git switch feature/user-login
Switched to branch 'feature/user-login'

# Create and switch in one step (recommended!)
git switch -c feature/user-registration
Switched to a new branch 'feature/user-registration'

# View all branches (including remote branches)
git branch -a
* feature/user-registration
  feature/user-login
  main
  remotes/origin/main

# View the last commit of each branch
git branch -v
* feature/user-registration  f4e5d6c feat: add welcome message
  feature/user-login  f4e5d6c feat: add welcome message
  main             f4e5d6c feat: add welcome message

📝 Note: Older versions of Git used git checkout to switch branches. Git 2.23+ introduced git switch (for switching branches) and git restore (for restoring files), with clearer semantics. git checkout is still available, but it took on too many responsibilities (switching branches + restoring files + creating branches), which could be confusing.

Branch Naming Conventions

A good branch name is like a good filename — you can tell what it's for at a glance.

bash
# Recommended naming format: <type>/<description>

# ✅ Good names
feature/user-login
feature/product-search
bugfix/fix-login-timeout
hotfix/fix-payment-vulnerability
release/v1.2.0
experiment/new-homepage-design

# ❌ Bad names
git branch test
git branch my-branch
git branch fix
git branch temp
git branch aaa

Deleting Branches

bash
# Delete a branch after feature development is complete
git switch main
git branch -d feature/user-login
Deleted branch feature/user-login (was b2c3d4e).

# If the branch hasn't been merged, Git will prevent deletion
git branch -d feature/user-registration
error: The branch 'feature/user-registration' is not fully merged.
If you are sure you want to delete it, run 'git branch -D'.

# Force delete (are you sure you don't want it?)
git branch -D feature/user-registration
Deleted branch feature/user-registration (was f4e5d6c).

💡 Tip: -d (lowercase) is safe deletion — only merged branches can be deleted. -D (uppercase) is force deletion. Think of door locks — -d is a regular lock, -D is kicking the door open.