Git: Stop Juggling Branches with Git Worktrees
Sun, Apr 27, 2025Working on multiple branches at once can be a bottleneck. Especially with the advent of agentic AI tooling where working on multiple problems at the same time are possible.
The typical git approach involves disruptive context switching with git stash
and git checkout
.
However, there’s another workflow, git worktree
.
What are Git Worktrees?
Git worktrees make it possible to have multiple working directories connected to the same repository. Creating a new worktree is fast because they share the same .git
directory. Each worktree can be on a different branch, letting you work on multiple tasks simultaneously.
The Bare Repository Pattern
A clean approach uses a bare repository as the central hub.
Name the bare repository .git
so that it can be found automatically by the git worktree
commands.
# Create a directory for the repository
mkdir stellar-rpc
cd stellar-rpc
# Clone using the GitHub CLI
gh repo clone stellar/stellar-rpc .git -- --bare
# Or using git:
git clone --bare https://github.com/stellar/stellar-rpc .git
The directory now contains the repository’s Git database, but no working directory and no checked-out source files itself.
Adding Worktrees
When beginning a new task, create a worktree:
# Create a worktree for a specific issue
# This creates a directory 'feature-abc' AND a new branch 'feature-abc' based on HEAD
git worktree add feature-abc
cd feature-abc
# Now you're in a standard git working directory on the 'feature-abc' branch
git status
Need to work on another branch simultaneously?
# Go back to the parent directory
cd ..
# Create another worktree
git worktree add feature-xyz
# Or specify the branch name and what the branch will branch from
git worktree add -b feature-xyz feature-xyz main
There are now multiple working directories, each on its own branch, sharing the same repository:
stellar-rpc/
├── .git/ # The bare repo (shared Git database)
├── feature-abc/ # Working directory for feature-abc branch
└── feature-xyz/ # Working directory for feature-xyz branch
Next time you’re juggling multiple branches, give worktrees a try.