Appearance
Git Worktree Maintenance: Lifecycle, Cleanup, and Recovery at Scale
Worktrees let you check out multiple branches in parallel. That power comes with a cost: worktrees accumulate. A hotfix worktree from last sprint, a CI debug worktree you forgot to remove, a feature worktree for that abandoned branch. Left alone, they eat disk space, confuse git gc, and leave stale metadata behind.
This guide covers what to do when worktrees pile up. Not how to create them (the parallel-builds and feature-branches guides cover that), but how to keep them from becoming a problem.
Why worktree maintenance matters
Each worktree is a full checkout. A monorepo with node_modules, build artifacts, and vendor directories can be 2-5 GB per worktree. Five stale worktrees = 10-25 GB of wasted disk. The git worktree list command shows you what you have, but it doesn't tell you what's safe to delete.
Beyond disk space, stale worktree metadata makes git gc and git prune behave differently. Git's garbage collector keeps objects reachable from any worktree's HEAD, reflog, or index. An abandoned worktree with an old branch can prevent Git from pruning objects you'd rather see gone.
Reading the worktree list
bash
git worktree listOutput looks like this:
/home/devops/project abc1234 [main]
/home/devops/project/.worktrees/hotfix-def5678 [hotfix/CVE-2024-5678]
/home/devops/project/.worktrees/debug-ci 9f3a1bc (detached HEAD)
/home/devops/project/.worktrees/old-feature eeeffff [feature/abandoned]Four columns: path, HEAD SHA, branch or detached marker, and optional flags.
To see locked and prunable status:
bash
git worktree list --verboseThis adds two columns: locked (shows the lock reason if any) and prunable (shows why the worktree qualifies for pruning).
Locking worktrees to prevent accidental removal
When a worktree is actively in use, lock it. This prevents git worktree remove and git worktree prune from touching it.
bash
git worktree lock .worktrees/debug-payment --reason "Active CI debugging session"The reason shows up in git worktree list --verbose:
/home/devops/project/.worktrees/debug-payment abc1234 [feat/payment] locked: Active CI debugging sessionUnlock when you're done:
bash
git worktree unlock .worktrees/debug-paymentWithout --reason, the lock still works but the reason field is empty. Always add a reason. Two weeks from now you will not remember why you locked that worktree.
When to lock
- You are actively working in the worktree and stepping away.
- A CI pipeline is using the worktree (a build script checks it out, runs, and will remove it later).
- The worktree contains temporary artifacts you want to inspect before cleanup.
When not to lock
- The worktree is idle but you feel bad deleting it. Either finish the work or remove the worktree. Locking idle worktrees is how sprawl starts.
Pruning: how Git cleans up stale metadata
git worktree prune removes metadata for worktrees whose working directory no longer exists. If you delete a worktree directory with rm -rf instead of git worktree remove, the metadata stays in .git/worktrees/<id>/. That metadata is harmless but clutters the list and takes a few kilobytes.
bash
git worktree pruneThis scans .git/worktrees/ and removes any entry whose worktree path is missing from disk. It is safe to run at any time. It does not touch existing worktrees.
Automatic pruning
Git runs git worktree prune automatically as part of git gc. If you run git gc regularly (or have git maintenance enabled), stale metadata gets cleaned up without manual intervention.
Pruning with expiration
bash
git worktree prune --expire 30.days.agoThis removes metadata only for worktrees whose working directory has been missing for more than 30 days. Useful when you want a grace period before full cleanup.
What prune does NOT do
- It does not delete any working directory. If the directory still exists, the metadata stays.
- It does not delete branches. The branch checked out in a pruned worktree still exists. You must delete it separately with
git branch -d. - It does not reclaim objects. The objects reachable from the worktree's HEAD are still in the object database. If the branch was merged and deleted,
git gcwill eventually prune the objects.
Repairing worktrees after moving the parent directory
If you move the parent repo to a new path, all worktrees break. Their metadata files contain absolute paths to the old location. git worktree repair fixes them:
bash
# Move the entire repo + worktrees
mv ~/projects/myapp ~/archive/myapp
# Inside the new location, repair all worktrees
cd ~/archive/myapp
git worktree repair
# Or repair a specific worktree
git worktree repair .worktrees/debug-paymentWithout arguments, git worktree repair scans .git/worktrees/ and updates the paths. You can also pass the path of a specific worktree to repair only that one.
This also works if the .git file inside a worktree (yes, the worktree has a .git file, not a .git directory) points to the wrong admin directory:
bash
# Inside the worktree itself
cd ../hotfix-branch
git worktree repair ../The ../ tells repair where the main repo is. It then fixes the .git file in the worktree to point to the correct admin directory.
Worktree metadata anatomy
Each worktree stores its metadata in .git/worktrees/<id>/. The <id> is derived from the worktree path, sanitized. You rarely need to touch these files, but knowing they exist helps when things go wrong:
.git/worktrees/`<id>`/
HEAD # The worktree's HEAD
commondir # Relative path back to the main .git directory
gitdir # Absolute path to the worktree's .git file
index # The worktree's index (separate from main)
locked # Present if locked, contains reason text
refs/ # Per-worktree refs (worktree-specific HEAD reflog, etc.)
ORIG_HEAD # If applicableIf locked is missing, the worktree is not locked. If it exists, git worktree remove and git worktree prune will refuse to touch it unless you pass --force twice.
You can manually remove the locked file to unlock a worktree when git worktree unlock fails (rare, but happens if the worktree directory is already deleted):
bash
rm .git/worktrees/debug-payment/locked
git worktree pruneThe worktree.guessRemote config option
When you run git worktree add <path><branch>`` and the branch only exists on the remote, Git normally fails with:
fatal: invalid reference: `<branch>`Set worktree.guessRemote = true and Git will look up the remote tracking branch and create a local branch from it:
bash
git config --global worktree.guessRemote true
# Now this works even if feat/flag-rollout only exists on origin:
git worktree add ../flag-rollout feat/flag-rolloutThis is a quality-of-life setting for teams that create feature branches on the remote first (common in GitHub/GitLab PR workflows). Without it, you must write the full refspec:
bash
git worktree add ../flag-rollout origin/feat/flag-rolloutOr create the local branch first:
bash
git checkout -b feat/flag-rollout origin/feat/flag-rollout
git checkout main # switch back so the worktree can use the branch
git worktree add ../flag-rollout feat/flag-rolloutworktree.guessRemote eliminates that dance.
Worktree lifecycle patterns for CI
CI pipelines that use worktrees need discipline around cleanup. A failed pipeline halfway through should not orphan a worktree.
Pattern: Create, run, remove with EXIT trap
bash
#!/bin/bash
set -euo pipefail
WT=".worktrees/ci-build-$$"
trap 'git worktree remove --force "$WT" 2>/dev/null || true' EXIT
git worktree add "$WT" HEAD
cd "$WT"
npm ci
npm run build
npm testThe trap runs on normal exit, on set -e failure, and on SIGTERM/SIGINT. The --force flag ensures removal works even if the worktree has uncommitted changes (which it shouldn't if the script is well-behaved, but CI environments are messy). The || true swallows errors if the worktree was already removed.
Pattern: Lock during use, unlock and remove after
bash
WT=".worktrees/integration-test"
git worktree add "$WT" main
git worktree lock "$WT" --reason "CI integration test"
# Run tests
cd "$WT"
./run-integration-tests.sh
cd -
git worktree unlock "$WT"
git worktree remove "$WT"The lock prevents any concurrent process (another CI job, a developer) from pruning or removing the worktree while tests are running.
Pattern: Per-job worktree with unique name
bash
JOB_ID="${CI_JOB_ID:-$$}"
WT=".worktrees/build-${JOB_ID}"
# Clean up any leftover from a previous run of this job
git worktree remove --force "$WT" 2>/dev/null || true
git worktree add "$WT" HEAD
trap 'git worktree remove --force "$WT" 2>/dev/null || true' EXIT
cd "$WT"
make buildThe pre-emptive remove --force before add handles the case where a previous run crashed before the cleanup trap fired. The job ID ensures unique worktree names when multiple CI jobs run on the same runner.
Pattern: CI matrix with worktrees
yaml
# .forgejo/workflows/matrix-build.yaml
jobs:
build:
strategy:
matrix:
service: [auth, payments, inventory]
steps:
- run: |
WT=".worktrees/${{ matrix.service }}"
git worktree add "$WT" HEAD
trap 'git worktree remove --force "$WT" 2>/dev/null' EXIT
cd "$WT"
make build SERVICE=${{ matrix.service }}Bulk operations for worktree sprawl
When worktrees have accumulated over months, you need to audit what exists and clean up in bulk.
List all worktrees with disk usage
bash
git worktree list --verbose | while read path rest; do
size=$(du -sh "$path" 2>/dev/null | cut -f1)
echo "$size $path $rest"
doneFind stale worktrees (branch already merged)
bash
git worktree list | while read path head branch; do
branch=${branch#\[}
branch=${branch%\]}
if [ "$branch" != "(detached HEAD)" ]; then
if git merge-base --is-ancestor "$branch" main 2>/dev/null; then
echo "MERGED: $path ($branch)"
fi
fi
doneThis checks if each worktree's branch is an ancestor of main. If yes, the branch has been merged and the worktree is a candidate for removal.
Prune all worktrees older than N days
bash
git worktree list | while read path head rest; do
mtime=$(stat -c %Y "$path" 2>/dev/null || echo 0)
now=$(date +%s)
age=$(( (now - mtime) / 86400 ))
if [ "$age" -gt 30 ]; then
echo "Stale: $path ($age days old)"
git worktree remove --force "$path" 2>/dev/null && echo " Removed" || echo " Skipped (locked?)"
fi
doneThe --force flag overrides locks and dirty states. Use it with caution. Better to first list the stale worktrees, inspect them, then remove selectively.
Audit: worktrees without a corresponding branch
bash
git worktree list | while read path head branch; do
branch=${branch#\[}
branch=${branch%\]}
if [ "$branch" != "(detached HEAD)" ]; then
if ! git show-ref --verify "refs/heads/$branch" >/dev/null 2>&1; then
echo "ORPHANED: $path (branch '$branch' no longer exists)"
fi
fi
doneThis catches worktrees whose branches were deleted by someone else (or by an earlier cleanup). The worktree still exists but its branch is gone. These are safe to remove.
Recovery from common problems
Accidentally deleted a worktree directory
If you ran rm -rf .worktrees/debug-payment instead of git worktree remove, you have orphaned metadata:
bash
# Clean up the metadata
git worktree prune
# If the branch was unique to that worktree and you need it back:
git branch <branch-name> <sha-from-worktree-list>The worktree's last checked-out SHA is still in the old git worktree list output (if you still have the terminal). If not, check git reflog for the branch or git fsck --lost-found for dangling commits.
Moved the parent repo, now worktrees are broken
See the repair section above. git worktree repair fixes this in one command.
Worktree remove says "is dirty"
bash
git worktree remove --force .worktrees/old-worktree--force overrides the dirty worktree check. Use it when you know the changes are worthless. If the changes matter, go into the worktree, commit or stash them, then remove.
"fatal: '<path>' is a missing worktree" but the directory exists
The worktree metadata file (.git/worktrees/<id>/gitdir) points to the wrong path. Run git worktree repair from the main repo to fix it.
Worktree locked by a crashed process
A CI pipeline locked the worktree and crashed before it could unlock it:
bash
# Remove the lock manually
rm .git/worktrees/ci-build/locked
# Or use double-force on remove
git worktree remove --force .worktrees/ci-buildSingle --force is enough when the worktree is merely dirty. Double --force (used to be git worktree remove --force --force in older Git versions) was needed when the worktree was locked. In modern Git (2.35+), a single --force overrides both dirty state and locks.
How git gc interacts with worktrees
This is the most misunderstood part of worktree management.
git gc runs from any worktree and affects the shared object database. It keeps objects reachable from all worktrees. This means:
- An abandoned worktree with an old branch prevents GC from pruning those objects. The worktree's HEAD, reflog, and index all count as reachable references. If the worktree points to a commit that is otherwise unreachable,
git gckeeps it. git gcrunsgit worktree pruneautomatically. But only for worktrees whose directories are missing. Live worktrees with stale branches are untouched.- Worktree-specific refs (stored under
.git/worktrees/<id>/refs/) are scanned during GC. A worktree's reflog counts as a reachability root.
If you want git gc to reclaim space from old worktree branches, remove the worktrees first, then run git gc.
bash
# Remove stale worktrees
git worktree remove .worktrees/old-feature
# Remove the branch if it was merged
git branch -d feature/old-feature
# Now GC can prune the objects
git gc --aggressiveMaintenance and worktrees
git maintenance start sets up background jobs (hourly prefetch, daily commit-graph, weekly repack). These jobs run from the main worktree and respect all linked worktrees as reachability roots. The weekly repack will not prune objects needed by any worktree.
If you have many worktrees, the weekly git maintenance run --task=gc will take longer because it must scan each worktree's refs. This is expected. The alternative is to remove unused worktrees before the maintenance window.
Summary
| Task | Command |
|---|---|
| List worktrees with details | git worktree list --verbose |
| Lock a worktree | git worktree lock <path> --reason "..." |
| Unlock a worktree | git worktree unlock <path>`` |
| Prune stale metadata | git worktree prune |
| Prune with grace period | git worktree prune --expire 30.days.ago |
| Repair paths after move | git worktree repair [<path>] |
| Remove a worktree (safe) | git worktree remove <path>`` |
| Remove a worktree (forced) | git worktree remove --force <path>`` |
Clean up after accidental rm | git worktree prune |
| Guess remote branches | git config --global worktree.guessRemote true |
See also
docs/devops-workflows/git-worktree-parallel-builds.md- Creating worktrees for CI buildsdocs/devops-workflows/git-worktree-parallel-debug.md- Debugging CI with worktreesdocs/devops-workflows/git-worktree-feature-branches.md- Feature branch isolation with worktreesdocs/recipes/worktree-maintenance-quick.md- Quick reference cheat sheetscripts/wt-manage.sh- Automation script for worktree lifecycle managementgit-worktree(1)manual