Using Git Worktree to Manage Multiple Branches Efficiently
This article explains how Git worktree, a feature introduced in 2015, allows developers to maintain a single repository while working on multiple branches simultaneously, addressing common scenarios such as hot‑fixes, feature development, and environment switching, and provides practical commands and examples.
When developers need to switch between long‑running tests on main , hot‑fixes, or new features, the usual approaches—committing unfinished work or using git stash —can be cumbersome and error‑prone, especially in large projects with many environment variables.
Git worktree, supported since 2015, solves these problems by allowing multiple working trees to share a single repository. A worktree is essentially an additional checkout of a branch that lives in its own directory while still referencing the same .git data.
The most useful commands are:
git worktree add [-f] [--detach] [--checkout] [--lock] [-b
]
[
]
git worktree list [--porcelain]
git worktree remove [-f]
git worktree prune [-n] [-v] [--expire
]Before using worktrees, understand two Git concepts: a newly initialized repository has only one worktree called the main worktree , and any directory that contains a .git file actually points to the shared .git directory.
Example: from a repository root amend-crash-demo , running git worktree add ../feature/feature2 creates a new directory feature/feature2 with a .git file that points to .git/worktrees/feature2 . The new worktree can be checked out, committed, pushed, and it does not interfere with the main worktree.
If branch names contain slashes (e.g., feature/JIRAID-Title ), the -b option must be used to create the branch correctly: git worktree add -b "hotfix/JIRA234-fix-naming" ../hotfix/JIRA234-fix-naming .
To see all existing worktrees, run git worktree list , which shows the path, commit hash, and branch for each worktree, including the main one.
When a worktree is no longer needed, remove it with git worktree remove . If the worktree has uncommitted changes, add the -f flag to force removal. Finally, run git worktree prune to clean up any leftover administrative files.
In practice, organizing worktrees under dedicated directories (e.g., feature/ for feature worktrees and hotfix/ for hot‑fix worktrees) keeps the filesystem tidy and avoids accidental tracking of worktree files.
Two reflective questions are posed: can the main worktree be deleted, and how the .git/worktrees directory evolves with repeated creation and deletion of worktrees.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.