Branches are one of Git's most powerful features, enabling you to work on multiple features simultaneously, experiment without risk, and organize your development workflow. Think of branches as parallel universes for your project—each branch is an independent line of development where you can make changes without affecting other branches. In this lesson, you'll learn what branches really are, how to create and switch between them, and why they're essential for modern software development.
What Are Branches?
A branch in Git is a lightweight, movable pointer to a specific commit. Despite the name, it's not a copy of your files—it's simply a reference that points to a commit in your history.
The Mental Model
Think of your Git history as a timeline of commits:
A --- B --- C --- D --- E (main branch)The branch name main is just a label pointing to commit E (the most recent commit). When you create a new branch, you're just creating a new label:
A --- B --- C --- D --- E (main)
\
E (feature)Now you have two branches, both pointing to the same commit E. When you make a new commit on the feature branch:
A --- B --- C --- D --- E (main)
\
E --- F (feature)The feature branch moves forward to point to the new commit F, while main stays where it was.
Key Insight: Branches are incredibly lightweight in Git. Creating a branch takes less than a second and uses virtually no disk space because you're not copying files—you're just creating a 41-byte file containing a commit hash!
Why Branches Matter
Branches enable several crucial workflows:
- Isolated Development: Work on a new feature without breaking the main codebase
- Experimentation: Try risky changes in a branch; delete the branch if they don't work out
- Parallel Work: Multiple people (or you) can work on different features simultaneously
- Bug Fixes: Create a quick branch to fix a bug while keeping feature work separate
- Code Review: Branches make it easy to review changes before merging them
- Release Management: Maintain different versions of your software
🌳 Why 'Branches'?
The name "branch" comes from the tree analogy. Your main development line is the trunk, and branches split off to explore different directions. Unlike real tree branches though, Git branches can merge back together!
The Default Branch
When you initialize a Git repository with git init, Git automatically creates a default branch. Historically, this was called master, but modern Git versions use main.
Main vs Master: Many teams and platforms (including GitHub) now use main as the default branch name instead of master. They both serve the same purpose—it's just a naming convention. When you see either term in this tutorial, they're interchangeable.
The default branch typically represents your production-ready code or the main line of development. All other branches usually split off from and eventually merge back into this branch.
Viewing Branches
Let's start by looking at the branches in your repository.
List All Branches
git branchThis shows all local branches, with an asterisk marking your current branch:
* main
feature/login
bugfix/headerThe * indicates you're currently on the main branch.
Verbose Branch Information
See each branch with its last commit:
git branch -v* main a1b2c3d Fix navigation bug
feature/login f4e5d6c Add login form validation
bugfix/header c7d8e9f Fix header overflow on mobileAll Branches (Including Remote)
We'll cover remote branches later, but you can see them with:
git branch -aCreating Branches
Create a New Branch
To create a new branch, use:
git branch feature/user-profileThis creates a new branch called feature/user-profile pointing to your current commit. However, you're still on your original branch!
📝 Branch Naming Conventions
Common branch naming patterns:
feature/description- For new featuresbugfix/description- For bug fixeshotfix/description- For urgent production fixesexperiment/description- For experimentsrefactor/description- For code refactoring
Use lowercase with hyphens or slashes. Be descriptive but concise!
Check Your Branches
git branch feature/user-profile
* mainThe new branch exists, but you're still on main (notice the *).
Switching Between Branches
To actually work on a branch, you need to switch to it. Git provides two commands for this:
Using git switch (Modern, Recommended)
git switch feature/user-profileSwitched to branch 'feature/user-profile'Now when you check branches:
git branch* feature/user-profile
mainThe * moved! You're now on the feature/user-profile branch.
Using git checkout (Traditional)
The older way to switch branches (still widely used):
git checkout maingit switch vs git checkout:
git switch was introduced in Git 2.23 (2019) to make branch operations clearer. git checkout does many things (switch branches, restore files, create new branches), which can be confusing.
Modern approach:
git switch- For switching branchesgit restore- For restoring files
Both work, but git switch is more explicit and recommended for new learners!
Create and Switch in One Command
Instead of creating a branch and then switching to it, do both at once:
# Modern way
git switch -c feature/dark-mode
# Traditional way
git checkout -b feature/dark-modeThe -c flag (create) or -b flag creates the branch and switches to it immediately.
⚡ Productivity Tip
Most developers use the create-and-switch pattern 90% of the time. You rarely create a branch without immediately switching to it!
Working on a Branch
Once you're on a branch, everything works the same as before. Let's practice:
- Create and switch to a new branch:
git switch -c feature/contact-form- Make some changes:
Create a new file contact.html:
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<h1>Contact Form</h1>
<form>
<input type="text" placeholder="Your name" required>
<input type="email" placeholder="Your email" required>
<textarea placeholder="Your message"></textarea>
<button type="submit">Send</button>
</form>
</body>
</html>- Stage and commit your changes:
git add contact.html
git commit -m "Add contact form page"- Check your commit history:
git log --onelinef4e5d6c (HEAD -> feature/contact-form) Add contact form page
a1b2c3d (main) Fix navigation bug
c7d8e9f Update homepage designNotice that HEAD points to feature/contact-form, and this branch is one commit ahead of main.
- Switch back to main:
git switch main- Check if the file exists:
ls contact.htmlThe file doesn't exist on main! When you switched branches, Git updated your working directory to match the main branch, where contact.html was never created.
- Switch back to your feature branch:
git switch feature/contact-form
ls contact.htmlThe file is back! Git switched your working directory back to the feature branch state.
This is the magic of branches! Each branch maintains its own version of the project. You can switch between them instantly, and Git handles updating all your files.
Interactive Branch Visualization
Try this interactive tool to see how branches work:
Experiment with Git Branches
Create branches, make commits, and see how they relate
Commit Log
Add features
main • 11:30 AM
Initial commit
main • 10:00 AM
Branch Management
Renaming Branches
Rename the branch you're currently on:
git branch -m new-branch-nameRename a different branch:
git branch -m old-name new-nameDeleting Branches
Once you're done with a branch (usually after merging it), you can delete it:
# Safe delete (only if merged)
git branch -d branch-name
# Force delete (even if not merged)
git branch -D branch-nameBe Careful! You can't delete the branch you're currently on. Switch to a different branch first.
git switch main
git branch -d feature/contact-form🗑️ Don't Fear Deletion
Deleting a branch only removes the branch pointer—the commits themselves remain in Git's history (at least for a while). If you delete a branch by accident, you can usually recover it!
Viewing Branch Relationships
See which branches are merged into your current branch:
# Branches merged into current branch
git branch --merged
# Branches not yet merged
git branch --no-mergedThis helps you identify which branches can be safely deleted.
Important Notes About Switching Branches
Uncommitted Changes
Git won't let you switch branches if you have uncommitted changes that would be overwritten:
# Make some changes
echo "new content" > test.txt
# Try to switch branches
git switch mainerror: Your local changes to the following files would be overwritten by checkout:
test.txt
Please commit your changes or stash them before you switch branches.
AbortingYou have three options:
- Commit your changes:
git add test.txt
git commit -m "Update test file"
git switch main- Discard your changes:
git restore test.txt
git switch main- Stash your changes (we'll learn this later):
git stash
git switch main
# Later: git stash popClean Working Directory
Before switching branches, it's good practice to have a clean working directory:
# Check status
git status
# Should see:
# nothing to commit, working tree cleanCommon Branch Workflows
Feature Branch Workflow
The most common workflow: create a branch for each feature or task.
# Start working on a new feature
git switch -c feature/user-profile
# Make changes, commit often
git add .
git commit -m "Add profile page structure"
# More work...
git add .
git commit -m "Add profile edit functionality"
# When done, switch back to main
git switch main
# Merge your feature (next lesson!)
git merge feature/user-profile
# Delete the feature branch
git branch -d feature/user-profileBug Fix Workflow
Quickly fix a bug without disturbing your feature work:
# Currently working on a feature
git switch feature/dashboard
# Bug report comes in!
# Switch to main and create bug fix branch
git switch main
git switch -c bugfix/login-error
# Fix the bug
git add .
git commit -m "Fix login redirect error"
# Merge fix to main
git switch main
git merge bugfix/login-error
# Delete bug fix branch
git branch -d bugfix/login-error
# Go back to your feature work
git switch feature/dashboardExperiment Workflow
Try something risky without affecting your main work:
# Create experimental branch
git switch -c experiment/new-algorithm
# Try the new approach
# ... make changes ...
git commit -am "Try new sorting algorithm"
# Doesn't work well?
# Just delete the branch!
git switch main
git branch -D experiment/new-algorithm # Force delete
# Or if it worked:
git switch main
git merge experiment/new-algorithmBranch Best Practices
1. Use Descriptive Names
Good:
feature/user-authenticationbugfix/header-overflowrefactor/database-queries
Bad:
branch1temptestasdf
2. Keep Branches Short-Lived
Branches that live for weeks or months become hard to merge. Aim to complete, merge, and delete branches within days.
3. Commit Often on Branches
Make small, frequent commits on your feature branches. You can always clean up the history later if needed.
4. Keep Main Branch Stable
The main branch should always be in a working state. Only merge code that's tested and ready.
5. Delete Merged Branches
Once a branch is merged, delete it. This keeps your branch list clean and prevents confusion.
6. Pull Before Creating New Branches
When working with others (we'll learn this soon), always update your main branch before creating a new feature branch:
git switch main
git pull
git switch -c feature/new-featureUnderstanding HEAD with Branches
Remember HEAD from the previous lesson? When working with branches, HEAD typically points to the current branch, which points to a commit:
HEAD -> feature/login -> commit abc123You can see where HEAD points:
# See what HEAD points to
cat .git/HEAD
# Output:
# ref: refs/heads/feature/loginWhen you switch branches, HEAD moves:
git switch main
cat .git/HEAD
# Output:
# ref: refs/heads/mainPractice Branch Commands
Try these commands to practice working with branches:
Practice Git Branches
Experiment with creating and switching branches
Try these examples:
Common Branch Issues
Issue: Can't Switch Branches
Error: "Please commit your changes or stash them before you switch branches"
Solution: You have uncommitted changes. Either commit them, discard them, or stash them:
# Option 1: Commit
git add .
git commit -m "Work in progress"
# Option 2: Discard
git restore .
# Option 3: Stash (temporary storage)
git stashIssue: Branch Doesn't Exist
Error: "pathspec 'feature/login' did not match any file(s) known to git"
Solution: The branch doesn't exist. Check available branches:
git branch -aIssue: Deleted Branch by Accident
Problem: You accidentally deleted a branch
Solution: If the branch was merged, the commits still exist. If not merged, check the reflog:
# See recent HEAD movements
git reflog
# Find the commit where your branch was
# Create a new branch at that commit
git branch feature/recovered abc123Command Reference
Here's a quick reference of all branch commands:
# Viewing Branches
git branch # List local branches
git branch -v # List with last commit
git branch -a # List all (including remote)
git branch --merged # List merged branches
git branch --no-merged # List unmerged branches
# Creating Branches
git branch branch-name # Create new branch
git switch -c branch-name # Create and switch (modern)
git checkout -b branch-name # Create and switch (traditional)
# Switching Branches
git switch branch-name # Switch branches (modern)
git checkout branch-name # Switch branches (traditional)
git switch - # Switch to previous branch
# Managing Branches
git branch -m new-name # Rename current branch
git branch -m old new # Rename specific branch
git branch -d branch-name # Delete merged branch
git branch -D branch-name # Force delete branch
# Branch Information
git show-branch # Show branch relationships
git log --oneline --graph # Visual commit graphKey Takeaways
- Branches are lightweight pointers to commits, not copies of files
- Use
git branchto create branches and list them - Use
git switchorgit checkoutto switch branches - Each branch maintains its own version of your project
- Branches enable parallel development and experimentation
- Common patterns include feature branches, bug fix branches, and experiment branches
- Always commit or stash changes before switching branches
- Delete branches after merging to keep your repository clean
- HEAD points to your current branch, which points to a commit
- Branch operations in Git are extremely fast and lightweight
What's Next?
Excellent work! You now understand how to create and work with branches—one of Git's most powerful features. You can create isolated workspaces for different features, switch between them instantly, and organize your development workflow effectively.
But branches are only half the story. In the next lesson, we'll learn about merging branches. You'll discover how to combine the work from different branches, understand merge strategies, and handle the process of bringing feature branches back into your main codebase. This is where branches really prove their power!
🎯 Practice Assignment
Before the next lesson, practice working with branches:
- Create at least 3 different feature branches
- Make 2-3 commits on each branch
- Practice switching between branches and observing how files change
- Use
git log --oneline --graph --allto visualize your branches - Try renaming a branch
- Experiment with the interactive branch visualizer above
The more comfortable you are with branches, the easier merging will be!