Skip to content

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:

git worktree add ../worktree-feature-a feature-a

Add a worktree and create a new branch:

git worktree add -b hotfix-123 ../worktree-hotfix main

List all worktrees:

git worktree list

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:

cd ../worktree-feature-a && git log --oneline
cd /tmp/worktree-drill && git log --oneline

Remove a worktree when done:

git worktree remove ../worktree-feature-a
git worktree remove ../worktree-hotfix

Prune stale worktree references:

git worktree prune

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

Cleanup

cd /tmp
rm -rf /tmp/worktree-drill /tmp/worktree-feature-a /tmp/worktree-hotfix