Git Worktree: Multiple Branches Simultaneously
Learn: Git Worktree: Multiple Branches Simultaneously
Welcome to TopperBlog! 👋
I'm a tech content creator passionate about helping developers level up their careers and master cutting-edge technologies.
🎯 What I Write About:
• AI/ML Engineering & LLMs
• Web3 & Blockchain Development
• System Design & Architecture
• Interview Preparation (FAANG)
• Freelancing & Remote Work
• Modern Tech Stacks (Next.js, React, Rust, TypeScript)
• Performance Optimization & Best Practices
💼 Mission: Sharing practical, actionable insights that accelerate your tech career and maximize your earning potential.
📚 15+ In-Depth Guides covering everything from earning $10k/month as a freelancer to cracking FAANG interviews.
🌐 Let's connect and grow together in this amazing tech journey!
#TechBlogger #SoftwareEngineering #CareerGrowth #WebDevelopment #AIEngineering
Git Worktree: Multiple Branches Simultaneously (Or: How I Stopped Tab-Hopping and Learned to Love Parallel Development)
You know that feeling when you're deep in the zone, refactoring a gnarly authentication module, and your Slack explodes with "URGENT: Production bug in the payment flow"?
Your heart sinks. You know what comes next: the dreaded context switch dance.
git stash, pray you didn't forget anything important, git checkout hotfix-branch, fix the bug, commit, push, git checkout back to your feature branch, git stash pop, and... wait, what was I even doing? Oh right, authentication. Where was I again?
Checks last 47 browser tabs to remember the mental model.
If this sounds familiar, buckle up. I'm about to introduce you to Git's best-kept secret that'll make you wonder why you've been suffering all these years.
The Problem: Branch Switching is a Productivity Vampire
Let's be honest about what really happens when you switch branches:
The Technical Cost:
- Your IDE loses its mind re-indexing everything
- Docker containers need rebuilding because dependencies changed
- That
npm installtakes another 3 minutes (thanks, node_modules) - Your test database needs re-seeding
- Build artifacts? Gone. Rebuild time: 5 minutes.
The Mental Cost:
- You lose your flow state (studies say it takes 23 minutes to recover, but let's be real—it's more like an hour)
- You forget which files you had open
- That brilliant solution you were about to implement? Poof
- Your carefully arranged terminal tabs? Chaos.
I once watched a senior developer spend 45 minutes just getting back to where they were before an "urgent" bug fix that took 5 minutes to actually solve. The bug fix was trivial. The context switching was the real killer.
Why This Actually Matters (Beyond Your Sanity)
Here's the thing: modern development demands parallel work. You're not living in a world where you can leisurely work on one feature for three weeks uninterrupted.
Real scenarios that happen every single day:
- Code review limbo: Your PR is waiting for review, but you can't start new work because you might need to make changes
- The CI/CD waiting game: Tests are running on your branch (15 minutes), and you're just... sitting there? Watching the spinner?
- Emergency hotfixes: Production doesn't care about your feature branch
- Experimental branches: You want to try a risky refactor without nuking your stable work
- Client demos: "Can you show me the old version real quick?" (Narrator: It was not quick)
The traditional solution? Clone the repo multiple times. Congratulations, you now have:
- 5 copies of a 2GB repository
- Confusion about which folder is which
- Git remotes that may or may not be in sync
- Your SSD crying for mercy
There's a better way.
Enter Git Worktree: The Parallel Universe Feature
Git worktree lets you check out multiple branches of the same repository simultaneously, each in its own directory, but all sharing the same Git history.
Think of it like this: Instead of having one desk where you constantly shuffle papers around, you get multiple desks in the same office. Each desk has different work laid out, but they all share the same filing cabinet (your .git directory).
The magic: All worktrees share the same repository data. No duplication. No sync issues. Just pure, parallel productivity.
How It Actually Works (The Good Stuff)
Your First Worktree: Baby Steps
Let's say you're working on a feature branch called feature/new-dashboard:
# You're currently in your main repo
cd ~/projects/my-app
# Create a new worktree for a hotfix
git worktree add ../my-app-hotfix hotfix/payment-bug
What just happened?
Git created a new directory called my-app-hotfix right next to your main repo, checked out the hotfix/payment-bug branch there, and linked it to your main repository's Git database.
Now you can:
# Terminal 1: Continue your feature work
cd ~/projects/my-app
# Keep coding on feature/new-dashboard
# Terminal 2: Fix that urgent bug
cd ~/projects/my-app-hotfix
# Fix the bug, commit, push
No stashing. No switching. No rebuilding. Just pure, unadulterated parallel work.
Creating Worktrees Like a Pro
Create a worktree from an existing branch:
git worktree add ../my-app-feature-x feature/user-authentication
Create a worktree AND a new branch simultaneously:
git worktree add -b feature/new-api ../my-app-api
This creates a new branch called feature/new-api and checks it out in the new worktree. Chef's kiss. 🤌
Create a worktree from a specific commit:
git worktree add ../my-app-investigation abc123
Perfect for those "wait, when did this break?" investigations.
Managing Your Worktree Empire
List all your worktrees:
git worktree list
Output looks like:
/Users/you/projects/my-app abc123 [main]
/Users/you/projects/my-app-hotfix def456 [hotfix/payment-bug]
/Users/you/projects/my-app-feature-x 789ghi [feature/user-authentication]
Beautiful. You can see your entire parallel universe at a glance.
Remove a worktree when you're done:
# First, delete the directory
rm -rf ../my-app-hotfix
# Then tell Git to clean up
git worktree prune
Or do it in one command:
git worktree remove ../my-app-hotfix
Git will even warn you if you have uncommitted changes. It's got your back.
The Real-World Workflow
Here's how I actually use this day-to-day:
# Main repo: Always on main/master, always clean
~/projects/my-app (main)
# Feature work: Long-running branches
~/projects/my-app-features/dashboard
~/projects/my-app-features/api-v2
# Hotfixes: Quick in, quick out
~/projects/my-app-hotfix (temporary)
# Code reviews: Check out PRs without disrupting work
~/projects/my-app-review (temporary)
My morning routine:
- Pull latest main in the main worktree
- Rebase my feature branches (each in their own worktree)
- Start coding wherever I need to
When a hotfix comes in:
git worktree add ../my-app-hotfix -b hotfix/urgent-thing- Fix it
- Push it
git worktree remove ../my-app-hotfix- Back to feature work in 30 seconds
No context switching. No stashing. No "wait, where was I?"
The Gotchas (Because Nothing's Perfect)
You Can't Check Out the Same Branch Twice
Git won't let you check out the same branch in multiple worktrees. This is actually a feature—it prevents you from creating merge conflicts with yourself.
# This will fail if feature/dashboard is already checked out
git worktree add ../another-dashboard feature/dashboard
The error:
fatal: 'feature/dashboard' is already checked out at '/Users/you/projects/my-app-features/dashboard'
The solution: This is Git protecting you. If you need to work on the same code in two places, you probably want two different branches anyway.
Disk Space (But Not As Much As You Think)
Yes, you're creating multiple directories. But here's the beautiful part: they share the .git directory.
Traditional multiple clones:
- Repo 1: 2GB
- Repo 2: 2GB
- Repo 3: 2GB
- Total: 6GB
With worktrees:
- Main
.git: 2GB - Worktree 1: ~100MB (just the working files)
- Worktree 2: ~100MB
- Total: ~2.2GB
You're basically just storing the checked-out files, not the entire Git history multiple times.
IDE Confusion (Easily Solved)
Some IDEs get confused when you open multiple worktrees. They might share settings, or index the same files multiple times.
Solution: Open each worktree in a separate IDE window. Modern IDEs handle this beautifully:
# VS Code
code ~/projects/my-app
code ~/projects/my-app-hotfix
# IntelliJ/WebStorm
idea ~/projects/my-app
idea ~/projects/my-app-hotfix
Treat them as separate projects. Because they are.
Advanced Patterns (For the Brave)
The PR Review Worktree
Reviewing PRs without disrupting your work:
# Create a script: ~/bin/review-pr
#!/bin/bash
PR_NUMBER=$1
BRANCH_NAME="pr-$PR_NUMBER"
# Fetch the PR
git fetch origin pull/$PR_NUMBER/head:$BRANCH_NAME
# Create worktree
git worktree add ../my-app-review-$PR_NUMBER $BRANCH_NAME
# Open in IDE
code ../my-app-review-$PR_NUMBER
echo "Review PR #$PR_NUMBER in ../my-app-review-$PR_NUMBER"
Usage:
review-pr 1234
Boom. PR checked out, IDE opened, your feature work untouched.
The Experiment Worktree
Want to try a risky refactor without committing to it?
git worktree add -b experiment/crazy-idea ../my-app-experiment
cd ../my-app-experiment
# Go wild. Break things. Learn stuff.
# If it works:
git push origin experiment/crazy-idea
# Create PR, merge it
# If it doesn't:
cd ~/projects/my-app
git worktree remove ../my-app-experiment
git branch -D experiment/crazy-idea
No harm, no foul. Your main work was never touched.
The CI/CD Waiting Room
Tests running on CI? Don't wait:
# Push your feature
git push origin feature/new-thing
# Immediately start new work
git worktree add -b feature/next-thing ../my-app-next
# When CI finishes and you need to fix something:
cd ~/projects/my-app # Your original worktree
# Make fixes, push again
The "Oh Crap" Emergency Worktree
Production is on fire, but you have uncommitted work:
# Don't stash. Don't commit half-baked code.
# Just create a hotfix worktree:
git worktree add ../my-app-emergency -b hotfix/production-fire
cd ../my-app-emergency
# Fix production
# Commit, push, deploy
# Back to your feature work
cd ~/projects/my-app
# Everything exactly as you left it
Real Wisdom from the Trenches
After using worktrees for two years, here's what I've learned:
1. Keep Your Main Worktree Sacred
Your main repository directory should always be on main/master and always clean. This is your source of truth, your safe space.
# In main worktree, create an alias
git config alias.sync '!git fetch origin && git reset --hard origin/main'
# Now you can always get back to a clean state
git sync
2. Name Your Worktrees Descriptively
Don't do this:
../my-app-1
../my-app-2
../my-app-temp
Do this:
../my-app-features/user-auth
../my-app-hotfix-payment
../my-app-review-pr-1234
Future you will thank present you.
3. Clean Up Regularly
Worktrees are cheap to create and destroy. Don't hoard them:
# Weekly cleanup script
git worktree list | grep -v "$(pwd)" | while read path rest; do
echo "Found worktree: $path"
read -p "Remove? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
git worktree remove "$path"
fi
done
4. Use Worktrees for Different Environments
# Development environment
~/projects/my-app-dev (feature/new-stuff)
# Staging environment
~/projects/my-app-staging (staging branch)
# Production debugging
~/projects/my-app-prod (production tag)
Each can have its own .env file, its own database, its own Docker containers. No conflicts.
5. Combine with Git Hooks
Create a post-checkout hook that runs in each worktree:
# .git/hooks/post-checkout
#!/bin/bash
echo "Checked out in worktree: $(pwd)"
# Install dependencies if package.json changed
if git diff --name-only HEAD@{1} HEAD | grep -q "package.json"; then
echo "package.json changed, running npm install..."
npm install
fi
The Performance Boost You Didn't Know You Needed
Let's talk numbers. Before worktrees, my typical "urgent hotfix" workflow:
- Stash changes: 10 seconds
- Switch branch: 5 seconds
- IDE re-index: 30 seconds
- Rebuild project: 2 minutes
- Fix bug: 5 minutes
- Commit & push: 10 seconds
- Switch back: 5 seconds
- IDE re-index: 30 seconds
- Rebuild project: 2 minutes
- Pop stash: 10 seconds
- Remember what I was doing: 10 minutes
Total: ~20 minutes for a 5-minute fix.
With worktrees:
cd ../my-app-hotfix: 1 second- Fix bug: 5 minutes
- Commit & push: 10 seconds
cdback: 1 second
Total: ~5 minutes.
That's a 75% time savings. And that's just one hotfix. Multiply that by every context switch in a week, and you're saving hours.
Common Questions (That You're Definitely Thinking)
Q: Is this just for big projects?
Nope. Even small projects benefit. The overhead is minimal, and the mental clarity is priceless.
Q: What about submodules?
Worktrees work with submodules, but each worktree gets its own submodule checkouts. Be aware of disk space if you have large submodules.
Q: Can I use this with GitHub Desktop / GitKraken / etc?
Most GUI tools don't have first-class worktree support yet. But they won't break anything—worktrees are just directories with Git repos. You might need to open each worktree as a separate repository in your GUI tool.
Q: What if I delete a worktree directory by accident?
Git tracks worktrees. Run git worktree prune and Git will clean up the references. Your commits are safe in the shared .git directory.
Q: Does this work on Windows?
Absolutely. Worktrees are a core Git feature and work identically on Windows, Mac, and Linux.
Your Action Plan (Do This Today)
Don't just read this and move on. Try it right now:
Step 1: Create your first worktree (2 minutes)
cd your-project
git worktree add ../your-project-experiment -b experiment/worktree-test
cd ../your-project-experiment
echo "Worktrees are awesome!" > test.txt
git add test.txt
git commit -m "Testing worktrees"
Step 2: See your worktrees
cd your-project
git worktree list
Step 3: Clean up
git worktree remove ../your-project-experiment
git branch -D experiment/worktree-test
Step 4: Set up your real workflow
Create a directory structure that makes sense:
mkdir -p ~/projects/my-app-worktrees
cd ~/projects/my-app
git worktree add ../my-app-worktrees/feature-1 -b feature/first-real-worktree
Step 5: Add aliases to make it easier
git config --global alias.wt 'worktree'
git config --global alias.wtl 'worktree list'
git config --global alias.wta 'worktree add'
git config --global alias.wtr 'worktree remove'
# Now you can:
git wta ../my-app-feature -b feature/new-thing
git wtl
git wtr ../my-app-feature
The Bottom Line
Git worktree isn't just a feature—it's a workflow revolution. It's the difference between:
- Juggling (stash, switch, unstash, repeat)
- Multitasking (multiple desks, same office)
You wouldn't ask a chef to cook three dishes on one burner, constantly moving pots around. You'd give them multiple burners. Worktrees are your multiple burners.
The next time someone pings you with "urgent bug, need fix ASAP" while you're deep in feature work, you won't feel that sinking dread. You'll just type:
git worktree add ../my-app-hotfix -b hotfix/urgent
And keep your flow state intact.
Your future self—the one who's shipping features faster, context-switching less, and actually enjoying development again—will thank you.
Now go forth and parallelize. Your productivity (and sanity) will never be the same.
P.S. - If you found this helpful, your teammates probably need to read it too. Share it. Save them from the stash-switch-unstash cycle. Be the hero they need.