git worktree add: Usage, Options & Common CI Errors
git worktree add gives you a second working directory backed by the same repository.
Worktrees let a pipeline build several branches in parallel without re-cloning. Each tree has its own checkout but shares the object store, saving time and disk.
What it does
git worktree add creates a new working directory linked to the current repository, checking out a branch or commit there. The new tree shares objects and refs with the main one.
Common usage
git worktree add ../feature feature
git worktree add -b hotfix ../hotfix main
git worktree add --detach ../inspect <sha>
git worktree add --track -b local ../local origin/remoteOptions
| Flag | What it does |
|---|---|
| <path> [<branch>] | Create a worktree at path on a branch |
| -b <name> | Create a new branch for the worktree |
| --detach | Check out a commit in detached HEAD |
| --track | Set up upstream tracking |
| -f / --force | Allow an already-checked-out branch |
Common errors in CI
fatal: '<branch>' is already checked out at '<path>' - a branch can be checked out in only one worktree at a time; use a different branch or --force. fatal: '<path>' already exists means the target directory is non-empty; pick a clean path.
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 detached