Skip to content
Latchkey

git worktree --detach: Parallel Checkouts in CI

git worktree add --detach <path> <commit> creates a second working tree at a detached HEAD so a job can have two checkouts at once.

When a build needs the base branch and the PR branch on disk simultaneously, a detached worktree avoids a second clone. The --detach flag skips branch checkout so the same branch can stay checked out in the main tree.

What it does

git worktree add attaches an extra working directory linked to the same .git. With --detach it checks out the given commit at a detached HEAD instead of a branch, which lets you materialize a ref that is already checked out elsewhere (git refuses to check the same branch out in two trees).

Common usage

Terminal
git worktree add --detach ../base origin/main
git worktree add -b pr-123 ../pr origin/pr-123
# clean up when the job is done
git worktree remove ../base
git worktree prune

Options

FlagWhat it does
--detachCheck out at a detached HEAD instead of a branch
-b <branch>Create and check out a new branch in the worktree
--forceAllow adding even if the path or branch is in use
listList existing worktrees and their HEADs
remove <path>Delete a worktree
pruneRemove administrative entries for deleted worktrees

In CI

On a shallow clone (fetch-depth: 1) the commit you target may not exist locally; fetch it first with git fetch --depth 1 origin <ref>. Always git worktree remove or prune before the job ends so cached checkouts on a persistent runner do not accumulate stale .git/worktrees entries.

Common errors in CI

"fatal: 'origin/main' is already checked out at ..." means you tried to attach the branch in a second tree; use --detach. "fatal: invalid reference: origin/pr-123" on a shallow clone means the ref was never fetched. "fatal: '../base' already exists" means a leftover worktree from a prior run; prune or remove it first.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →