Sub topic 2
New branches, detached HEAD and choosing a starting point
Assume you know commits, branches, remotes, and the difference between the working directory, index, and repository history.
A worktree can start from an existing branch, a new branch, or a commit without a branch. Choose the form that matches the work:
# Create and switch to a new branch from main
git worktree add ../myproject-hotfix -b hotfix/login-crash main
# Check out an existing branch
git worktree add ../myproject-feature feature/search
# Create a read-only review worktree at a remote-tracking commit
git fetch origin
git worktree add --detach ../myproject-review origin/feature/searchThe -b option creates the branch before checking it out. The final argument, such as main, selects the starting commit. An existing branch must not already be checked out in another worktree.
A detached HEAD points directly to a commit instead of a local branch. It is useful for reviewing or testing a known revision. Avoid making important commits there unless you create a branch first.
What worktrees share and what they keep separate
Linked worktrees share the object database, references, and commit history. A commit created in one worktree is available to the others. Each worktree has its own checked-out files, index, HEAD, and untracked files.
git rev-parse --git-dir
git rev-parse --git-common-dirIn a linked worktree, the first command identifies its private administrative directory. The second identifies the repository-wide administrative directory.
Ignored dependency directories and untracked files are also per worktree. Run each worktree's setup commands when it needs its own dependencies.
Removing worktrees and pruning stale metadata
Remove a clean worktree from its parent repository:
git worktree remove ../myproject-feature
git worktree pruneremove deletes the worktree and its metadata. prune removes administrative entries for directories deleted outside Git. Check the path before removing it, because local uncommitted files may be lost.
Exercise
Which command should you use for a read-only review of origin/feature/search without claiming that branch?
Show answer
Use git worktree add --detach ../review origin/feature/search.