Skip to content

Instantly share code, notes, and snippets.

@Mondonno
Last active October 1, 2025 11:30
Show Gist options
  • Save Mondonno/05d2f03997b6852e50ec8d56fa4435e8 to your computer and use it in GitHub Desktop.
Save Mondonno/05d2f03997b6852e50ec8d56fa4435e8 to your computer and use it in GitHub Desktop.
Git Worktrees: Zero → Productive

Git Worktrees: Zero → Productive

Worktrees let you check out multiple branches of the same repo into different directories, without stashing or switching back and forth.
Perfect for: hotfixes, reviews, long tests, parallel dev or parallel AI coding (with Codex CLI, Claude Code, etc.).


1. Prep Once

From your repo root:

# make a sibling folder for worktrees
mkdir -p ../myrepo-wt
git fetch --all -p

2. Create a Worktree

New feature branch from main:

git worktree add -b feat/x ../myrepo-wt/feat-x origin/main
cd ../myrepo-wt/feat-x

➡️ Now you have two working dirs:

  • ./ → main repo (your normal workspace)
  • ../myrepo-wt/feat-x → feature branch workspace

Both share the same .git database.


3. Common Patterns

Parallel task (no stash needed):

git worktree add -b hotfix/ssl ../myrepo-wt/hotfix-ssl origin/release

Code review (clean checkout):

git fetch origin pull/123/head:pr/123
git worktree add ../myrepo-wt/pr-123 pr/123

Long-running tests / perf experiments:

git worktree add ../myrepo-wt/tests origin/main

4. Push Safely

Push only the current branch (avoid leaking all branches):

git push origin HEAD --follow-tags

5. Clean Up

When a branch is merged:

git worktree remove ../myrepo-wt/feat-x
git branch -d feat/x
git worktree prune --expire=now

6. Golden Rules

  • One branch per worktree — you can’t check out the same branch twice.
  • Each worktree = one purpose (feature, review, hotfix, test).
  • Don’t git push --all casually — use HEAD unless you really want to mirror.
  • Prune old trees regularly with git worktree prune.

7. Quick Reference

git worktree list
git worktree add -b <branch> ../repo-wt/<branch> [start-point]
git worktree add ../repo-wt/tmp --detach <commit>
git worktree remove ../repo-wt/<branch>
git worktree prune --expire=now

8. Mental Model

.git (shared history & branches)
├── main-repo/        (main workspace)
└── repo-wt/
    ├── feat-x/       (feature branch)
    ├── hotfix-ssl/   (hotfix branch)
    └── pr-123/       (code review)

Branches and commits sync instantly between worktrees.
Each folder has its own working dir, build artifacts, editor settings, etc.


ONE-LINER TO REMEMBER:

git worktree add -b <branch> ../repo-wt/<branch> origin/main → parallel workspace, no stash needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment