Drill: Work on Multiple Branches with git worktree¶
Goal¶
Use git worktree to check out multiple branches simultaneously in separate directories without stashing or switching.
Setup¶
- A git repository with multiple branches
- Enough disk space for additional working trees
Commands¶
Set up a practice scenario:
mkdir /tmp/worktree-drill && cd /tmp/worktree-drill && git init
echo "main content" > file.txt && git add file.txt && git commit -m "initial"
git checkout -b feature-a && echo "feature a" >> file.txt && git add . && git commit -m "feature a"
git checkout -b feature-b main && echo "feature b" >> file.txt && git add . && git commit -m "feature b"
git checkout main
Add a worktree for a branch:
Add a worktree and create a new branch:
List all worktrees:
Now work in separate directories simultaneously:
# Terminal 1: work on feature-a
ls ../worktree-feature-a/
# Terminal 2: work on hotfix
ls ../worktree-hotfix/
Each worktree is a full working directory:
Remove a worktree when done:
Prune stale worktree references:
What to Look For¶
- Each worktree has its own working directory and index but shares the same .git object store
- You cannot check out the same branch in two worktrees simultaneously
- Commits made in any worktree are visible from all worktrees
- Worktrees avoid the cost of stashing, switching, and rebuilding
Common Mistakes¶
- Trying to check out a branch that is already checked out in another worktree
- Forgetting to remove worktrees after finishing, leaving stale directories
- Not realizing that worktrees share refs (pushing from any worktree pushes the same remote)
- Deleting the worktree directory manually instead of using
git worktree remove