Git worktree = Have several working folders for the SAME repo.
Concept:
Analogy: It is like having several desks for the same project.
Classic problem:
# You are working on feature-A
git checkout feature-A
# Code, code, code... (unfinished work)
# EMERGENCY: bug on main!
git stash # Save work in progress
git checkout main # Switch to main
# Fix the bug...
git checkout feature-A # Go back to your work
git stash pop # Recover your work in progressWorktree solution:
# You are working on feature-A in the main folder
# Emergency? Create a new folder for main!
git worktree add ../hotfix main
# Now:
# - ./ → feature-A (your work continues)
# - ../hotfix → main (for the urgent fix)Benefit: No stash/switch. Just 2 folders, 2 parallel tasks!
mkdir demo-worktree && cd demo-worktree
git init
echo "print('main v1')" > app.py
git add . && git commit -m "Main version"
# Create a feature branch
git checkout -b feature-new
echo "print('feature work')" > feature.py
git add . && git commit -m "Feature work"
git checkout main# Create a worktree for feature-new
git worktree add ../feature-work feature-new
# Create a worktree for a new branch
git worktree add ../hotfix-branch -b hotfix
# See all worktrees
git worktree listdemo-worktree/ → main branch
../feature-work/ → feature-new branch
../hotfix-branch/ → hotfix branch (new)# Terminal 1: Main folder (main)
cd demo-worktree
echo "print('main updated')" >> app.py
git add . && git commit -m "Update main"
# Terminal 2: Feature work
cd ../feature-work
echo "print('feature complete')" >> feature.py
git add . && git commit -m "Complete feature"
# Terminal 3: Hotfix
cd ../hotfix-branch
echo "print('urgent fix')" > fix.py
git add . && git commit -m "Critical fix"Magic: 3 branches, 3 folders, 0 context switching!
| Command | Action |
|---|---|
git worktree add <path> <branch> | Create a worktree on an existing branch |
git worktree add <path> -b <new-branch> | Create a worktree + new branch |
git worktree list | See all worktrees |
git worktree remove <path> | Delete a worktree |
git worktree prune | Clean up deleted worktrees |
1. Urgent hotfix:
git worktree add ../hotfix main
cd ../hotfix && echo "fix" > fix.py
git add . && git commit -m "Hotfix"
git push origin main2. PR review:
git worktree add ../pr-review pr-branch
cd ../pr-review # Test the PR without disturbing your work3. Branch comparison:
git worktree add ../version-a branch-a
git worktree add ../version-b branch-b
# Compare files between ../version-a and ../version-bgit worktree remove ../feature-work
git worktree remove ../hotfix-branch
git worktree prune # Clean up referencesWorktree = Git multitasking without compromise!