Git Worktree: Managing Multiple Working Directories

 
 
  • Gérald Barré

Git worktree is a powerful feature that allows you to have multiple working directories associated with a single repository. Instead of switching branches and potentially losing uncommitted work, you can check out different branches in separate directories simultaneously without recloning the repository.

Git worktree creates additional working trees linked to the same repository. Each worktree can have a different branch checked out, allowing you to work on multiple features, bug fixes, or experiments without the overhead of cloning the entire repository multiple times. The main point is that you only have one git index (.git directory), reducing disk space usage and improving performance.

When you're in the flow of coding, switching contexts can be disruptive. Git worktree helps by:

  • Preserving context: Keep your current work intact while quickly switching to fix a bug or review code
  • Parallel development: Work on multiple features simultaneously without branch switching overhead
  • Agent coding: You can let an AI agent work on a separate branch while you continue your current tasks
  • Reduced cognitive load: No need to stash or commit incomplete work when switching tasks
  • Comparing files: Easily compare changes across branches without needing to switch back and forth. You can have multiple versions of the same file open in different worktrees, making it easier to see how changes affect your code.

To create a new worktree:

Shell
# Create a worktree for an existing branch
git worktree add ../feature-branch feature-branch

# Create a worktree with a new branch from the main branch
git worktree add -b new-feature ../new-feature origin/main

To delete a worktree, you can use:

Shell
# Remove a worktree
git worktree remove ../feature-branch

# Or delete the directory and clean up:
rm -rf ../feature-branch
git worktree prune

You can also list all worktrees with:

Shell
# List all worktrees
git worktree list

Best practices for using Git worktree:

  • Keep worktrees in a predictable location (e.g., sibling directories)
  • Use descriptive directory names that match branch names
  • Clean up unused worktrees regularly to avoid clutter

Git worktree is an underutilized feature that can significantly improve your development workflow, especially when you need to maintain multiple contexts simultaneously.

#VS Code

VS Code recently added support for Git worktrees. You may need to enable it in your settings: https://code.visualstudio.com/updates/v1_103#_git-worktree-support

Then, you can use the UI to create or delete worktrees:

Create a worktree in VS CodeCreate a worktree in VS Code

Delete a worktree in VS CodeDelete a worktree in VS Code

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub