Git Worktree: Work on Multiple Branches Simultaneously
Use git worktree to check out multiple branches at once in separate directories. No more stashing or committing before switching branches.
git worktree add ../hotfix-branch hotfix/urgent-fixDetailed Explanation
What Does git worktree Do?
git worktree lets you check out multiple branches of the same repository simultaneously, each in its own directory. Every worktree shares the same .git data, so there is no duplication of the object database.
Creating a Worktree
# Check out an existing branch in a new directory
git worktree add ../hotfix-branch hotfix/urgent-fix
# Create a new branch in a new worktree
git worktree add -b feature/new-feature ../new-feature
Listing Worktrees
git worktree list
# /home/user/project abc1234 [main]
# /home/user/hotfix-branch def5678 [hotfix/urgent-fix]
Removing a Worktree
# Remove when done
git worktree remove ../hotfix-branch
# Force remove if there are changes
git worktree remove --force ../hotfix-branch
# Prune stale worktree references
git worktree prune
Why Use Worktrees?
Without worktrees, switching branches requires either committing incomplete work, stashing, or losing changes. With worktrees, you can:
- Work on a hotfix while your feature branch stays open in another terminal.
- Run tests on one branch while developing on another.
- Compare behavior between branches side-by-side.
Worktree vs. Multiple Clones
| Worktree | Separate Clone | |
|---|---|---|
| Disk usage | Shares objects | Duplicates everything |
| Branch locking | Cannot check out same branch twice | No restrictions |
| Setup time | Instant | Requires full clone |
Limitations
Each branch can only be checked out in one worktree at a time. If you need the same branch in two places, you must use a separate clone. Also, worktrees share the staging area configuration, so be mindful of global git hooks.
Worktrees are one of Git's most underused features. Once you try them, switching branches the old way feels painful.
Use Case
A developer is deep in a feature branch when a critical production bug is reported. They create a worktree for the hotfix branch, fix the bug, and return to their feature work without losing context.