Appearance
Recipe: Worktree Maintenance and Lifecycle Management
bash
# List all worktrees with lock/prunable status
git worktree list --verbose
# Lock a worktree to protect it from removal
git worktree lock .worktrees/debug-payment --reason "Active CI debugging session"
# Unlock when done
git worktree unlock .worktrees/debug-payment
# Prune stale metadata (orphaned worktree entries)
git worktree prune
# Prune with 30-day grace period
git worktree prune --expire 30.days.ago
# Repair worktrees after moving the parent directory
git worktree repair
# Remove a worktree (safe)
git worktree remove .worktrees/old-feature
# Remove a worktree (forced - overrides dirty/locked)
git worktree remove --force .worktrees/old-feature
# Auto-resolve remote branches when adding
git config --global worktree.guessRemote true
# Check which worktree branches are merged into main
git worktree list | while read p h b; do b=${b#[}; b=${b%]}; \
[ "$b" != "(detached HEAD)" ] && git merge-base --is-ancestor "$b" main \
&& echo "MERGED: $p ($b)"; done
# Find orphaned worktrees (branch no longer exists)
git worktree list | while read p h b; do b=${b#[}; b=${b%]}; \
[ "$b" != "(detached HEAD)" ] && ! git show-ref --verify "refs/heads/$b" >/dev/null 2>&1 \
&& echo "ORPHANED: $p ($b)"; done
# Remove all stale worktrees older than 30 days
git worktree list | while read p h r; do \
mtime=$(stat -c %Y "$p" 2>/dev/null || echo 0); \
age=$(( ($(date +%s) - mtime) / 86400 )); \
[ "$age" -gt 30 ] && git worktree remove --force "$p" 2>/dev/null; done
# CI pattern: create, use, clean up via EXIT trap
trap 'git worktree remove --force .worktrees/ci-$$ 2>/dev/null || true' EXIT
git worktree add .worktrees/ci-$$ HEAD
cd .worktrees/ci-$$
# ... build/test ...
cd -