Using Git Worktree to Manage Multiple Branches Without Cloning Multiple Repositories
This article explains how Git worktree lets developers maintain a single repository while simultaneously working on multiple branches—such as features, hotfixes, or testing environments—without the overhead of cloning multiple repos, and provides practical commands and examples for effective workflow management.
Developers often need to switch between feature development, hotfixes, and long-running tests, which can be disruptive when using a single Git checkout or multiple cloned repositories. The article introduces git worktree , a Git feature introduced in 2015 that allows multiple working trees to share a single repository.
Key commands include:
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 (the main worktree), and each directory used with Git contains either a .git folder or a .git file pointing to the actual worktree data.
Example: creating a worktree for a new feature branch.
cd amend-crash-demo
git worktree add ../feature/feature2This creates a new directory ../feature/feature2 with its own .git file that references the shared repository. The new branch can be checked out, committed, and pushed independently of the main worktree.
When branch names contain slashes (e.g., feature/JIRAID-Title ), use the -b option to avoid creating nested directories:
git worktree add -b "hotfix/JIRA234-fix-naming" ../hotfix/JIRA234-fix-namingListing all worktrees is done with git worktree list , which shows the path, commit hash, and branch for each worktree, including the main worktree.
/Users/rgyb/Documents/projects/amend-crash-demo 82b8711 [main]
/Users/rgyb/Documents/projects/feature/feature2 82b8711 [feature2]
/Users/rgyb/Documents/projects/hotfix/JIRA234-fix-naming 82b8711 [hotfix/JIRA234-fix-naming]To remove a worktree, run git worktree remove <path> . If the worktree has uncommitted changes, add the -f flag to force removal.
git worktree remove -f hotfix/JIRA234-fix-namingFinally, git worktree prune cleans up any leftover administrative files from deleted worktrees, keeping the repository tidy.
The complete workflow consists of the four commands above: git worktree add , git worktree list , git worktree remove , and git worktree prune . Using a single repository with multiple worktrees simplifies branch management, reduces disk usage, and avoids the complications of maintaining multiple cloned repos.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
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.