git worktree Command: Parallel Checkouts in CI
git worktree attaches additional working trees to a single repository, each on its own ref.
A matrix CI job that needs two branches at once (for example to diff or build both) can use worktrees to avoid a second clone, sharing object storage between trees.
Common flags
add <path> <ref>- create a new working tree at path checked out to refadd --detach <path> <commit>- add a detached worktree at a commitlist- show all working trees and their HEADsremove <path>- remove a worktreeprune- clean up administrative records of deleted worktrees--force- override safety checks when adding or removing
Example
# Build current branch and main side by side without recloning
git worktree add ../main-tree origin/main
( cd ../main-tree && make build )
git worktree remove ../main-treeIn CI
Worktrees share the object database, so a second worktree is far cheaper than a second clone when a job needs two refs at once. Remember to git worktree remove (or prune) at the end so cached repos do not accumulate stale trees.
Using this in CI
CI checkouts are shallow and detached by default, which changes the answer this command gives you. Commands that read history, branch names, or tags need the checkout configured for it.
- uses: actions/checkout@v4
with:
fetch-depth: 0 # history, tags, and git describe all need this
- run: |
git rev-parse --is-shallow-repository # expect false
git rev-parse --abbrev-ref HEAD # prints HEAD when detachedKey takeaways
- git worktree add gives a second checkout that shares objects, avoiding a reclone.
- It is ideal for jobs that must build or diff two refs simultaneously.
- Clean up with worktree remove or prune on reused runners.