0
0
GitHow-ToBeginner · 4 min read

How to Use Git Worktree: Manage Multiple Branches Easily

Use git worktree add <path> <branch> to create a new working directory linked to a branch. This lets you work on multiple branches at once without switching branches in a single folder.
📐

Syntax

The basic syntax of git worktree commands includes:

  • git worktree add <path> <branch>: Adds a new working directory at path for the specified branch.
  • git worktree list: Lists all linked working directories.
  • git worktree remove <path>: Removes a linked working directory.
bash
git worktree add <path> <branch>
git worktree list
git worktree remove <path>
💻

Example

This example shows how to create a new worktree for a branch named feature in a separate folder, then list all worktrees.

bash
git clone https://github.com/example/repo.git
cd repo
# Create and switch to a new branch 'feature'
git checkout -b feature
# Add a new worktree in '../repo-feature' for 'feature' branch
git worktree add ../repo-feature feature
# List all worktrees
git worktree list
Output
/full/path/to/repo HEAD /full/path/to/repo-feature feature
⚠️

Common Pitfalls

Common mistakes when using git worktree include:

  • Trying to add a worktree for a branch that does not exist locally or remotely.
  • Deleting the worktree folder manually instead of using git worktree remove, which can leave git metadata inconsistent.
  • Working on the same branch in multiple worktrees, which can cause conflicts.
bash
## Wrong: Adding worktree for a non-existent branch
# git worktree add ../repo-bad non-existent-branch
# Error: fatal: 'non-existent-branch' is not a commit and a branch 'non-existent-branch' cannot be created from it

## Right: Create branch first, then add worktree
# git branch new-branch
# git worktree add ../repo-new new-branch
📊

Quick Reference

CommandDescription
git worktree add Create a new working directory for a branch
git worktree listShow all linked worktrees
git worktree remove Remove a linked worktree safely
git worktree pruneClean up stale worktrees

Key Takeaways

Use git worktree to work on multiple branches simultaneously without switching folders.
Always create the branch before adding a worktree for it.
Remove worktrees with git worktree remove to keep git metadata clean.
List your worktrees with git worktree list to see all active work directories.
Avoid working on the same branch in multiple worktrees to prevent conflicts.