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
-
Add a new worktree:
git worktree add ../path-to-new-worktree branch-name -
List existing worktrees:
git worktree list -
Remove a worktree when done:
git worktree remove path-to-worktree
Step-by-Step Instructions
-
Navigate to your repository (where you’re working on main):
cd /path/to/your/repo -
Create a new worktree for your feature branch:
git worktree add ../repo-feature-branch feature-branch- This creates a new directory named
repo-feature-branchalongside your current repository - If the branch doesn’t exist yet, add
-bto create it:git worktree add -b new-feature-branch ../repo-feature-branch
- This creates a new directory named
-
Navigate to your new worktree:
cd ../repo-feature-branch -
Work on your feature branch - make changes, commit, push as normal.
-
Switch between worktrees as needed by simply changing directories.
-
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 pruneto 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