0
0
Gitdevops~15 mins

Creating a worktree in Git - Mechanics & Internals

Choose your learning style9 modes available
Overview - Creating a worktree
What is it?
Creating a worktree in git means making a new working directory linked to the same repository. This allows you to have multiple places to work on different branches or commits without switching back and forth in one folder. Each worktree acts like a separate workspace but shares the same history and data. It helps you work on several tasks at once without confusion.
Why it matters
Without worktrees, you would have to constantly switch branches in a single folder, which can be slow and risky if you forget to commit changes. Worktrees let you keep multiple branches open side-by-side, making it easier to test, develop, or review code in parallel. This saves time and reduces mistakes, especially in complex projects or when juggling many features.
Where it fits
Before learning about worktrees, you should understand basic git concepts like repositories, branches, and commits. After mastering worktrees, you can explore advanced git workflows, continuous integration setups, and multi-branch development strategies.
Mental Model
Core Idea
A git worktree is like having multiple linked work desks for the same project, each showing a different branch or commit, so you can work on many things at once without mixing them up.
Think of it like...
Imagine a shared office with one filing cabinet (the git repository) but several desks (worktrees). Each desk has the files arranged differently for a specific task, but they all pull from the same cabinet. You can work at any desk without moving files back and forth.
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│ Worktree 1    │   │ Worktree 2    │   │ Worktree 3    │
│ (branch A)    │   │ (branch B)    │   │ (branch C)    │
└──────┬────────┘   └──────┬────────┘   └──────┬────────┘
       │                   │                   │
       ▼                   ▼                   ▼
  ┌─────────────────────────────────────────────┐
  │               Git Repository                 │
  │ (all branches, commits, and history stored) │
  └─────────────────────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding git branches and working directory
🤔
Concept: Learn what branches and the working directory are in git.
A git branch is a pointer to a commit, representing a line of development. The working directory is the folder where files are checked out for editing. Normally, you have one working directory per repository, and you switch branches inside it.
Result
You know that switching branches changes the files in your working directory to match that branch's state.
Understanding branches and the working directory is essential because worktrees create multiple working directories linked to the same repository.
2
FoundationLimitations of single working directory
🤔
Concept: Recognize why having only one working directory can be a problem.
When you switch branches in one folder, uncommitted changes can cause conflicts or be lost. Also, switching takes time, and you can't work on two branches simultaneously in the same folder.
Result
You see that working on multiple branches at once is difficult without separate spaces.
Knowing these limits motivates the need for multiple workspaces, which worktrees provide.
3
IntermediateCreating a new worktree with git worktree add
🤔Before reading on: do you think creating a worktree copies the entire repository or just links to it? Commit to your answer.
Concept: Learn how to create a new worktree linked to a branch or commit.
Use the command: git worktree add This creates a new folder at with the files checked out from the specified branch or commit. It shares the repository data, so it doesn't duplicate the whole repo.
Result
A new folder appears with the branch's files, ready for editing independently from other worktrees.
Understanding that worktrees share repository data saves disk space and allows fast switching between branches.
4
IntermediateListing and managing multiple worktrees
🤔Before reading on: do you think git automatically cleans up worktrees when you delete their folders? Commit to your answer.
Concept: Learn how to see all worktrees and remove them properly.
Use git worktree list to see all active worktrees and their paths. To remove a worktree, first delete its folder, then run git worktree prune to clean references. Git does not automatically remove worktrees if you just delete folders.
Result
You can track and clean up worktrees safely without corrupting the repository.
Knowing how to manage worktrees prevents orphaned references and keeps the repo healthy.
5
AdvancedWorking with detached HEAD in worktrees
🤔Before reading on: can you create a worktree on a commit without a branch? What happens then? Commit your guess.
Concept: Understand how worktrees can point to commits without branches (detached HEAD).
You can create a worktree on any commit hash, not just branches. This puts the worktree in detached HEAD state, meaning commits here won't update any branch unless you create one. This is useful for testing or temporary changes.
Result
You get a worktree checked out at a specific commit, isolated from branches.
Knowing detached HEAD worktrees helps you experiment safely without affecting main branches.
6
ExpertInternal linking and storage optimization of worktrees
🤔Before reading on: do you think each worktree has its own full .git folder? Commit your answer.
Concept: Learn how git internally links worktrees to the main repository to save space and maintain consistency.
Worktrees do not have full .git folders. Instead, they have a small .git file pointing to the main repository's git directory plus metadata about the worktree. This design avoids duplicating objects and keeps all worktrees synchronized with the same history.
Result
Multiple worktrees efficiently share data, reducing disk usage and ensuring consistent repository state.
Understanding this internal linking explains why worktrees are lightweight and safe to use concurrently.
Under the Hood
Git stores all data (commits, branches, objects) in a single .git directory. Each worktree has its own working directory but a minimal .git file that points back to the main .git directory. This file includes information about the worktree's branch or commit. When you run git commands inside a worktree, git uses this pointer to access the shared repository data. This avoids duplicating objects and keeps all worktrees consistent.
Why designed this way?
This design was chosen to save disk space and improve performance. Instead of copying the entire repository for each worktree, git uses references to share data. It also simplifies synchronization and reduces errors from having multiple independent repositories. Alternatives like cloning the repo multiple times waste space and complicate updates.
Main Repository (.git directory)
┌─────────────────────────────────────────────┐
│                                             │
│  ┌───────────────┐   ┌───────────────┐      │
│  │ Worktree 1    │   │ Worktree 2    │      │
│  │ (working dir) │   │ (working dir) │      │
│  │ .git file --->│   │ .git file --->│      │
│  │ points to main│   │ points to main│      │
│  └───────────────┘   └───────────────┘      │
│                                             │
│  Shared objects, refs, commits, branches    │
│  stored once in main .git directory         │
└─────────────────────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does creating a worktree duplicate the entire git repository on disk? Commit yes or no.
Common Belief:Creating a worktree copies the whole repository, so it uses a lot of disk space.
Tap to reveal reality
Reality:Worktrees share the same repository data and only create a new working directory with a pointer to the main .git folder, saving disk space.
Why it matters:Believing this leads to unnecessary cloning of repos and wasted disk space instead of using efficient worktrees.
Quick: If you delete a worktree folder manually, does git automatically remove its record? Commit yes or no.
Common Belief:Deleting the worktree folder removes it completely from git's awareness.
Tap to reveal reality
Reality:Git keeps references to deleted worktrees until you run git worktree prune, which cleans up stale entries.
Why it matters:Ignoring this causes cluttered git metadata and possible confusion about active worktrees.
Quick: Can you create a worktree on any commit, even without a branch? Commit yes or no.
Common Belief:Worktrees must be created only on branches.
Tap to reveal reality
Reality:You can create worktrees on any commit, resulting in a detached HEAD state.
Why it matters:Not knowing this limits flexible testing and temporary work scenarios.
Quick: Does each worktree have its own independent git history? Commit yes or no.
Common Belief:Each worktree is like a separate repository with its own history.
Tap to reveal reality
Reality:All worktrees share the same git history and objects from the main repository.
Why it matters:Misunderstanding this can cause confusion about commits and branch synchronization.
Expert Zone
1
Worktrees can be used to test pull requests or patches without affecting your main workspace, enabling safer code reviews.
2
Git enforces that a branch can only be checked out in one worktree at a time to prevent conflicts, but detached HEAD worktrees bypass this restriction.
3
Worktrees can speed up CI pipelines by allowing parallel builds on different branches without cloning the repository multiple times.
When NOT to use
Avoid worktrees if you need completely isolated repositories with separate histories or configurations; in such cases, cloning is better. Also, for very large monorepos with complex submodules, worktrees might complicate management.
Production Patterns
Teams use worktrees to maintain stable release branches alongside active development branches on the same machine. Developers open multiple worktrees to work on features, bug fixes, and experiments simultaneously. CI systems use worktrees to run tests on different branches efficiently without full clones.
Connections
Virtual Machines
Both provide isolated environments for work but at different scales and purposes.
Understanding worktrees as lightweight isolated workspaces helps appreciate how virtual machines isolate entire operating systems, showing different levels of isolation.
File System Hard Links
Worktrees share repository data similarly to how hard links share the same file data without duplication.
Knowing how hard links save space by pointing to the same data clarifies why worktrees are efficient and lightweight.
Project Management Kanban Boards
Worktrees allow parallel work on different tasks like Kanban boards let teams track multiple tasks simultaneously.
Seeing worktrees as parallel task spaces helps understand managing multiple development streams without mixing progress.
Common Pitfalls
#1Deleting a worktree folder without cleaning git references.
Wrong approach:rm -rf /path/to/worktree
Correct approach:rm -rf /path/to/worktree git worktree prune
Root cause:Not knowing git keeps metadata about worktrees separately, so manual cleanup is needed to avoid stale references.
#2Trying to check out the same branch in two worktrees simultaneously.
Wrong approach:git worktree add ../wt1 feature-branch git worktree add ../wt2 feature-branch
Correct approach:git worktree add ../wt1 feature-branch git worktree add ../wt2 -b feature-branch-copy origin/feature-branch
Root cause:Git restricts one branch per worktree to prevent conflicts; creating a new branch copy avoids this.
#3Assuming worktrees duplicate the entire repository and wasting disk space by cloning instead.
Wrong approach:git clone repo repo-copy cd repo-copy # work on branch
Correct approach:git worktree add ../new-worktree branch-name cd ../new-worktree # work on branch
Root cause:Misunderstanding worktree sharing leads to inefficient use of disk and time.
Key Takeaways
Git worktrees let you have multiple working directories linked to the same repository, enabling parallel work on different branches or commits.
Worktrees share the repository data, so they are lightweight and save disk space compared to cloning multiple repos.
You must manage worktrees carefully, cleaning up references and respecting branch checkout rules to avoid conflicts.
Worktrees support detached HEAD states, allowing safe experimentation without affecting branches.
Understanding worktrees improves your workflow efficiency, especially when juggling multiple tasks or integrating continuous integration.