Git worktree allows you to work on multiple branches of the same repository simultaneously without needing to stash or commit incomplete changes. Here’s how to set it up:

Basic Worktree Commands

  1. Add a new worktree:

    git worktree add ../path-to-new-worktree branch-name
  2. List existing worktrees:

    git worktree list
  3. Remove a worktree when done:

    git worktree remove path-to-worktree

Step-by-Step Instructions

  1. Navigate to your repository (where you’re working on main):

    cd /path/to/your/repo
  2. Create a new worktree for your feature branch:

    git worktree add ../repo-feature-branch feature-branch
    • This creates a new directory named repo-feature-branch alongside your current repository
    • If the branch doesn’t exist yet, add -b to create it:
      git worktree add -b new-feature-branch ../repo-feature-branch
  3. Navigate to your new worktree:

    cd ../repo-feature-branch
  4. Work on your feature branch - make changes, commit, push as normal.

  5. Switch between worktrees as needed by simply changing directories.

  6. Clean up when finished:

    git worktree remove ../repo-feature-branch
    • Note: You must commit, stash, or discard changes before removing a worktree

Best Practices

  • Use relative paths (../) or absolute paths to avoid confusion
  • Use descriptive directory names that indicate the branch purpose
  • Clean up old worktrees with git worktree prune to remove references to deleted worktrees
  • Don’t nest worktrees inside other worktrees

Advanced Usage

  • Create a worktree from a specific commit:

    git worktree add -b hotfix ../repo-hotfix a1b2c3d
  • Add a lightweight worktree (no branch checkout, detached HEAD):

    git worktree add --detach ../repo-experiment
  • Lock a worktree to prevent it from being pruned:

    git worktree lock ../repo-feature-branch

Linked Map of Contexts