Each linked worktree has a private sub-directory in the repository’s
$GIT_DIR/worktrees directory. The private sub-directory’s name is usually
the base name of the linked worktree’s path, possibly appended with a
number to make it unique. For example, when $GIT_DIR=/path/main/.git the
command git worktree add /path/other/test-next next creates the linked
worktree in /path/other/test-next and also creates a
$GIT_DIR/worktrees/test-next directory (or $GIT_DIR/worktrees/test-next1
if test-next is already taken).
Within a linked worktree, $GIT_DIR is set to point to this private
directory (e.g. /path/main/.git/worktrees/test-next in the example) and
$GIT_COMMON_DIR is set to point back to the main worktree’s $GIT_DIR
(e.g. /path/main/.git). These settings are made in a .git file located at
the top directory of the linked worktree.
Path resolution via git rev-parse --git-path uses either
$GIT_DIR or $GIT_COMMON_DIR depending on the path. For example, in the
linked worktree git rev-parse --git-path HEAD returns
/path/main/.git/worktrees/test-next/HEAD (not
/path/other/test-next/.git/HEAD or /path/main/.git/HEAD) while git
rev-parse --git-path refs/heads/master uses
$GIT_COMMON_DIR and returns /path/main/.git/refs/heads/master,
since refs are shared across all worktrees, except refs/bisect,
refs/worktree and refs/rewritten.
See gitrepository-layout(5) for more information. The rule of
thumb is do not make any assumption about whether a path belongs to
$GIT_DIR or $GIT_COMMON_DIR when you need to directly access something
inside $GIT_DIR. Use git rev-parse --git-path to get the final path.
If you manually move a linked worktree, you need to update the gitdir file
in the entry’s directory. For example, if a linked worktree is moved
to /newpath/test-next and its .git file points to
/path/main/.git/worktrees/test-next, then update
/path/main/.git/worktrees/test-next/gitdir to reference /newpath/test-next
instead. Better yet, run git worktree repair to reestablish the connection
automatically.
To prevent a $GIT_DIR/worktrees entry from being pruned (which
can be useful in some situations, such as when the
entry’s worktree is stored on a portable device), use the
git worktree lock command, which adds a file named
locked to the entry’s directory. The file contains the reason in
plain text. For example, if a linked worktree’s .git file points
to /path/main/.git/worktrees/test-next then a file named
/path/main/.git/worktrees/test-next/locked will prevent the
test-next entry from being pruned. See
gitrepository-layout(5) for details.
When extensions.worktreeConfig is enabled, the config file
.git/worktrees/<id>/config.worktree is read after .git/config is.